Attribute selectors, JavaScript and IE8

笑着哭i 提交于 2019-12-19 19:48:37

问题


I'm attempting to use attribute selectors and CSS for formatting elements.

The HTML looks like:

<div id="user" highlight="false">User Name</div>

The CSS is:

[highlight=true]
{
    background-color: red;
}

[highlight=false]
{
    background-color: white;
}

And then there's some accompanying JavaScript:

if( foo )
{
    node.setAttribute('highlight', true);
}
else
{
    node.setAttribute('highlight', false);
}

This works in Firefox and Chrome. When the highlight attribute gets changed by the JavaScript, the element's background color changes as appropriate. In IE8, however, it's a different story. The element will display correctly according to the highlight value that is initially assigned in the HTML, but when the attribute is changed dynamically the display of the element doesn't change.

Is this a known quirk, and is there a known work-around?

Update I just changed the attribute name to "frob" with values "on" and "off." That should settle any issue about reserved or interpretable values.

One other thing of note. When I turn on the IE8 developer tools and use the HTML inspector, it will show the style [frob=on] or [frob=off] as applied for whatever value frob had when I started the document inspector. However, the frob attribute will then no longer change in the inspector view. In no case do the values in the [frob=on/off] css ever get applied after the initial render of the HTML.

Update: Problem Solved The solution is to force a redraw. There are various ways of doing this, but it appears the standard one is to reassign the className to itself.


回答1:


You're using unknown attribute hightlight. It's IE so it supports attributes according to its name (what's seems to be harder than supports every attribute name, but... it's IE).

Just use class="hightlight" - easier to implement and deal with.




回答2:


You are setting the attribute to JavaScript true and false, not string "true" and "false". This could be interpreted by the browser as 1 and 0 and lead to unwanted results.

Can you try

node.setAttribute('highlight', 'true');

?




回答3:


to avoid inevitable cross-browser compatibility issue's with javascript/css I would recommend using jQuery.

For example, to highlight an element via the jQuery framework this is all that it takes...

$("div").click(function () {
      $(this).effect("highlight", {}, 3000);
});



回答4:


Make sure you have DOCTYPE defined at the top of the page: Css attribute selector for input type="button" not working on IE7




回答5:


Check to make sure you have a DOCTYPE defined at the top of your page: Css attribute selector for input type="button" not working on IE7



来源:https://stackoverflow.com/questions/2112783/attribute-selectors-javascript-and-ie8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!