动态设置' float:left'在DOM节点上将无法在IE8中工作

时间:2015-11-17 03:01:14

标签: javascript css internet-explorer-8

我创建了两个DOM节点elemA和elemB,并将它们附加到容器节点,在此之前,我在elemA上设置float样式,elemB使用js代码,结果不起作用;另一方面,如果我删除elemA.style['float'] = 'left'elemB.style['float'] = 'left',并使用css设置浮点数,它可以工作,我无法弄清楚为什么?



var container = document.querySelector('#container');
var elemA = document.createElement('div');
var elemB = document.createElement('div');

elemA.className='elem-a';
elemA.style['float'] = 'left';
elemA.style['width'] = '45px';
elemA.style['height'] = '75px';
elemA.style['backgroundColor'] = 'green';
elemA.innerHTML = 'A';

elemB.className='elem-b'
elemB.style['float'] = 'left';
elemB.style['width'] = '45px';
elemB.style['height'] = '75px';
elemB.style['backgroundColor'] = 'blue';
elemB.style['marginLeft'] = '20px';
elemB.innerHTML = 'B';

container.appendChild(elemA);
container.appendChild(elemB);

.elem-a {
  float: left;
}

.elem-b {
  float: left;
}

<div id="container" style="width:200px;height:200px;border:1px solid red;">
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

如关于IE8的评论中所述,您应该使用现代浏览器

IE期望styleFloat属性,而其他浏览器使用cssFloat,因此您应该在代码中使用两者来支持IE,因为您可以看到我已在代码中注释掉了。

<!DOCTYPE html>
    <meta http-equiv="X-UA-Compatible"  content="IT=edge,chrome=IE8">

    <meta charset='utf-8'>
    <body>
    <div id="container" style="width:200px;height:200px;border:1px solid red;"></div>
    <script type="text/javascript">

        var container = document.querySelector('#container');
        var elemA = document.createElement('div');
        var elemB = document.createElement('div');

        elemA.className='elem-a';
        elemA.style.styleFloat = 'left';//For IE
        elemA.style['float'] = 'left';
        elemA.style['width'] = '45px';
        elemA.style['height'] = '75px';
        elemA.style['backgroundColor'] = 'green';
        elemA.style['display']='block';
        elemA.innerHTML = 'A';

        elemB.className='elem-b'
        elemB.style.styleFloat = 'left';//For IE
        elemB.style['float'] = 'left';
        elemB.style['width'] = '45px';
        elemB.style['height'] = '75px';
        elemB.style['backgroundColor'] = 'blue';
        elemB.style['marginLeft'] = '20px';
        elemB.style['display']='block';
        elemB.innerHTML = 'B';

        container.appendChild(elemA);
        container.appendChild(elemB);
    </script>
    </body>
</html>