javascript - 如果有条件,如何使用 JavaScript 比较 css 样式值?

标签 javascript html css

我有一个简短的问题。如果我想将样式左/右值与另一个坐标(比方说鼠标)进行比较,我该怎么做?

这是我在没有鼠标坐标的情况下尝试的方法,但由于某种原因我的条件从未执行...

<style>
    #container
    {
        position:absolute;
        left:400px;
        top:200px;
    }
</style>

<script>
function moveExit(){    
    var containerId = document.getElementById("container").style;

    if(containerId.left == 400 + "px")
        containerId.left = 395 + "px";  
}
</script>

这是我的 body :

<body>
    <div id="container">
    <img
    src="Images/image.jpg"
    onmouseover="moveExit();"
    />
    </div>
</body>

这是我第一次使用 javascript。谢谢!

最佳答案

为此您需要使用计算样式。

How do I get a computed style?

var left = window.getComputedStyle(document.getElementById("container")).left

对于 IE8,您必须使用 currentStyle 属性,因为不支持计算样式。

document.getElementById("container").currentStyle.left

Cross-browser (IE8-) getComputedStyle with Javascript?

关于javascript - 如果有条件,如何使用 JavaScript 比较 css 样式值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17956693/

相关文章:

javascript - 在带有自屏幕的 window.open 中传递变量

javascript - Bootstrap 多重选择在 AngularJS 中不起作用

html - 如何将右栏(桌面)分成两部分,一个显示在手机顶部,另一个显示在底部?

c# - HTML anchor 替换为 RegEx

javascript - requestanimationframe() 中的函数调用了太多次,如何只调用一次?

css - 将自定义样式表应用于 QWebView

html - 使用具有等高列的 anchor 隐藏内容

javascript - CSS 模块在 Codesandbox 中不起作用 - 即使文件存在也无法找到

javascript - 如何获取对动态添加元素的引用?

javascript - 通过javascript删除不需要的文本