且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

IE7和setAttribute()删除类

更新时间:2023-12-05 14:18:22

setAttribute()getAttribute()通常在IE 7和更早版本(以及更高版本中的兼容模式)中损坏.请使用元素的className属性:

elementZoomButtonIn.className = "zoom-icon zoom-icon-small zoom-button-in";

即使setAttribute()getAttribute()在IE中没有损坏,但使用等效的DOM属性代替通常更容易,更可靠.

I've got a pretty interesting issue. I'm writing a plugin which allows you to zoom in/out an image. I've got 3 buttons: close (close the 'window'), zoom in, zoom out. The buttons zoom in/out have got disabled versions, too. Its activated when you reach the minimum/maximum amount of zoom.

If you open the picture to zoom, you can see an active zoom out button, and a disabled zoom in button (because I set the maximum value at opening). When you first clicked on the zoom out button, the zoom in button should get rid of disabled class. It works fine in Safara, Chrome, Firefox 3.6/4/5, IE8 but not in IE7.

The zoom in button has an ID and classes and I want to force IE7 to remove specific classes from the element. First, I used removeClass(), but it didn't work. Then I use setAttribute(), which works in every browser but IE7.

Here is the example. So, when you open the image to zoom, the zoom out button has ID="zoom-button-in" and 5 classes: zoom-icon, zoom-icon-small, zoom-button-in, zoom-button-disabled, zoom-button-disabled-in. And I want to remove the 2 'disabled' classes. So I use this:

var elementZoomButtonIn = document.getElementById("zoom-button-in");
elementZoomButtonIn.setAttribute("class", "zoom-icon zoom-icon-small zoom-button-in");

I've tried to set the class empty before inserted the non-disabled classes, but didn't work.

Is this method working in IE7? (-:

Thank you, Guys!

setAttribute() and getAttribute() are generally broken in IE 7 and earlier (and compatibility modes in later versions). Use the element's className property instead:

elementZoomButtonIn.className = "zoom-icon zoom-icon-small zoom-button-in";

Even if setAttribute() and getAttribute() weren't broken in IE, it's still generally easier and more reliable to use equivalent DOM properties instead.