javascript - 通过 JavaScript 的 CSS : changing class "interrupted" by style change

标签 javascript html css

通过 JavaScript 更改 DIV 的类效果很好,直到我通过更改该 DIV 的样式属性来“中断它”。

case 0: left 变为 400

案例 1:改变 left 为 600

情况 2:不起作用!

这是为什么?

<!DOCTYPE html>
<html>

<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
    <style type="text/css">
        .pos1 {left: 200px; top:400px;}
        .pos2 {left: 400px; top:400px;}
        .pos3 {left: 800px; top:400px;}
    </style>
</head>

<body>
        <div id = "img" class = "pos1" style="position:absolute;"> <img src="gfx/1n.png"> </div>


        <script type="text/javascript">
            var action = 0;
            window.onmousedown = function(event){makeAction();}

            function makeAction() {
                switch(action) {
                    case 0: action++; document.getElementById('img').className = "pos2"; break
                    case 1: action++; document.getElementById('img').style.left = "600px"; break;
                    case 2: action++; document.getElementById('img').className = "pos3"; break;
                }

            }

        </script>
</body>
</html>

最佳答案

因为您在第二种情况下设置的样式属性会覆盖您在最后一种情况下分配的类的样式。

在第一种情况之后图像标签是

<img class="pos2" ... />

所以它位于左侧 400px。

在第二种情况之后图像标签是

<img class="pos2" style="left: 600px" ... />

即使它仍然具有 pos2 类,样式属性会覆盖 左侧定位,因此它现在位于左侧 600 像素处。

在最后一个案例之后,图像标签是:

<img class="pos3" style="left: 600px;" .. />

即使它现在有 pos3 类,样式属性仍然会覆盖左侧定位,因此它仍然位于左侧 600 像素处。

了解 CSS 不依赖于何时应用它,而是始终遵循特异性规则。并且规则声明标签样式属性中的样式规则覆盖类中的样式规则。

您可以使用 important 关键字覆盖规则:

.pos3 {left: 800px !important; top:400px;}

关于javascript - 通过 JavaScript 的 CSS : changing class "interrupted" by style change,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8771543/

相关文章:

javascript - 在 iframe 上使用新的 javascript performance.timing API?

java - mediaCapture windows 8.1 winjs 应用程序

html - 当设备尺寸较小时,<Div> 部分将不会保持包含状态

javascript - 将值从 Servlet 传递到 JSP 中的 onload JavaScript 函数

javascript - 在 JavaScript 中获取属性之前检查对象是否存在

html - 使用 css 和 html 的菜单栏

html - :nth-child doesn't work

html - 你如何重新排列 flex 元素?

javascript - 当提交按钮被隐藏时通过回车提交表单;在 Firefox 中工作,在 Chrome 中不执行任何操作

javascript - 使用 select() 复制值并复制