在Internet Explorer中,document.getElementById(...).setAttribute('style',...)无法正常工作。

6

在Internet Explorer 7.0中,document.getElementById(...).setAttribute('style',...)无法正常工作。我该如何让它在Internet Explorer中正常工作呢?

<!DOCTYPE html> 
<html lang="en"> 

<head>
<script type="text/javascript">
    var myarray=new Array(3);
    for (i=0; i <1000; i++){
        myarray[i]=new Array(3);
    }
    myarray[0][0]="new"; myarray[0][1]="old";

    function swapText(id){
        document.getElementById('id' + id).setAttribute('style', 'font-weight: bold; color: red; font-size:150%;');
        document.getElementById('id'+ id).innerHTML = myarray[id][0];
    }
    function originalText(id){
        document.getElementById('id' + id).setAttribute('style', 'color:' + 'black'  + ';');
        document.getElementById('id' + id).innerHTML = myarray[id][1];
    }
</script>
</head>
<body>
    <div id="scoreboard" border='1'> </div>
    <div id="qa">
        <div id="col1" class="column">  
            <div id="id0" onmouseover="swapText(0)"; onmouseout="originalText(0)">old</div>
        </div>
    </div>
</body>
</html>

你的代码中有一些 JavaScript 错误吗? - David Rodrigues
这并不真正回答问题,但你应该将这些CSS规则放在一个或两个类中,然后只需添加类即可。 - nathan gonzalez
David,没有错误。但是在IE中,样式影响不起作用...单词在IE中改变(从“旧”到“新”再回来),但样式更改不起作用。 - John R
4个回答

25

如果您希望更改在文档中得到反映,使用setAttribute是不可靠的。请使用Element.style

var el = document.getElementById('id' + id);
el.style.fontWeight = 'bold';
el.style.color = 'red';
el.style.fontSize = '150%';

等等类似的东西。


我想这是最好的解决方案。它兼容所有浏览器。 - David Rodrigues

1

使用jQuery

jQuery是一个非常强大的JavaScript库,让你用很少的代码就可以做到几乎任何事情。它的主要优点之一(除了其美丽的语法)是,它专门设计为平台和浏览器无关,因此您不必再担心这些问题。

在jQuery中完成与现在相同的操作可能看起来像这样:

function swapText(id) {
    $('#id' + id)
        .css('font-weight','bold').css('color','red').css('font-size','150%')
        .html(myarray[id][0]);
}

function originalText(id) {
    $('#id' + id).css('color','black').html(myarray[id][1]);
}

当然,如果您为“交换”样式定义了CSS类,则可以简单地使用 $('#id'+id).addClass('swapped'); 和 $('#id'+id).removeClass('swapped'); 。

此外,有一些非常好的方法来连接事件,因此如果您不想定义具有名称的函数,则无需这样做:

$('div').hover(function() { 
    $(this)
        .css('font-weight','bold').css('color','red').css('font-size','150%')
        .html(myarray[id][0]);
}, 
function() { 
    $('#id' + id).css('color','black').html(myarray[id][1]);
});

谢谢Tomas。我已经拖延学习jQuerry太久了。 - John R

0

你可以使用 setAttribute,它也兼容 IE-8 和 IE-7。

 var el = document.getElementById('id' + id);
 el.setAttribute('fontWeight','bold');
 el.setAttribute('color','red');
 el.setAttribute('fontSize','150%');

如果要为一个元素分配一个类,我建议按照以下方式进行:

 el.className = "class-name";

0

来自MSDN此属性无法通过脚本访问。要通过脚本访问样式,请使用样式对象


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接