document.getElementById(...)。setAttribute('style',...在Internet Explorer 7.0中不起作用。如何在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>
答案 0 :(得分:19)
如果您希望更改反映在文档中,则使用setAttribute
是不可靠的。请改用Element.style
:
var el = document.getElementById('id' + id);
el.style.fontWeight = 'bold';
el.style.color = 'red';
el.style.fontSize = '150%';
等等。
答案 1 :(得分:1)
使用jQuery。
jQuery是一个非常强大的JavaScript库,它可以让你用很少的代码做任何事情。它的一个主要优点(除了其漂亮的语法)是它专门设计为独立于平台和浏览器,所以你不必再担心任何这些了。</ p>
做同样的事情你现在做,但在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]);
});
答案 2 :(得分:0)
来自MSDN:无法通过脚本访问此属性。要通过脚本访问样式,请使用样式对象
答案 3 :(得分:0)
您可以使用与IE-8和IE-7兼容的setAttribute
var el = document.getElementById('id' + id);
el.setAttribute('fontWeight','bold');
el.setAttribute('color','red');
el.setAttribute('fontSize','150%');
为一个元素分配一个类,我建议按照
el.className = "class-name";