简体   繁体   English

在JavaScript中测试元素的style属性和css值之间有区别吗?

[英]Is there a difference between testing the style attribute of an element and the css value in JavaScript?

I'm trying to make a single-page website that uses arrow buttons on each side to scroll to different pseudo-pages. 我正在尝试制作一个单页面的网站,该网站的每一侧都使用箭头按钮滚动到不同的伪页面。 The left arrow has the CSS value visibility: hidden; 左箭头具有CSS值visibility: hidden; so that the use doesn't scroll into empty space. 这样使用不会滚动到空白处。 The button becomes visible once the user scrolls to the right, but I want to hide it again when the user scrolls back to the "homepage". 一旦用户向右滚动,该按钮将变为可见,但是当用户滚动回“主页”时,我想再次将其隐藏。 I'm using jQuery to test the left attribute like so: 我正在使用jQuery来测试left属性,如下所示:

if($('#box').css('left') == '0%') {
    $('.left').css('visibility', 'hidden');
}

Inspect Element on Firefox shows me that the left value when I want the button to disappear is indeed 0% , but it actually appears in the HTML tag, as style="left: 0%;" Firefox上的Inspect Element向我显示,当我希望按钮消失时,left值的确为0% ,但实际上它出现在HTML标记中,为style="left: 0%;" , because the value is assigned by the scroll mechanism I coded in JavaScript. ,因为该值是由我用JavaScript编码的滚动机制分配的。 Is there a different way to test for these style values versus a value on a CSS stylesheet? 与CSS样式表中的值相比,是否有其他方法可以测试这些style值?

change your code to the following: 将您的代码更改为以下内容:

 console.log('left is now = '+$('#box').css('left'))
 if($('#box').css('left') == '0%') {
   $('.left').css('visibility', 'hidden');
 }

This will give you three pieces of information: 这将为您提供三项信息:

1) are you actually hitting that if statement 2) when it does hit, what is the actual value being returned (and yes you may want to try computedStyle) 3) is the value what you expected. 1)您是否真的击中了if语句2)当它击中时,返回的实际值是多少(是的,您可能要尝试computeStyle)3)是您期望的值。

Armed with this info, you can quickly debug your problem. 有了此信息,您可以快速调试问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM