javascript - 在 DOM 节点上动态设置 'float:left' 在 IE8 中不起作用

标签 javascript css internet-explorer-8

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

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>

最佳答案

正如在关于 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>

关于javascript - 在 DOM 节点上动态设置 'float:left' 在 IE8 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33748414/

相关文章:

html - 通过 flexbox 或网格通过 CSS 定位将交替元素对齐到容器中的不同位置?

css - IE8 - 导航链接不工作

javascript - 当前页面刷新时选择的 div?

html - 如何创建一条从左到右穿过文本并带有过渡的线条?

CSS 3 过滤器(模糊)不使用过渡持续时间

css - 条件 css 无法针对 IE

asp.net - Windows 身份验证凭据框在 IE8 和 IIS7 中多次询问

javascript - 使用 javascript 合并 html 段落

javascript - 为什么立即调用函数表达式 (IIFE) 与自执行匿名函数不同?

javascript - 添加背景图片时文本区域变为透明