javascript - 尝试获取样式元素时未获得正确的输出

标签 javascript css

<分区>

我正在尝试根据先前的状态将 div 元素的可见性设置为可见或隐藏。即,当元素之前可见时,我试图将可见性设置为隐藏,反之亦然。

html:

<div id="cartwin"></div>

CSS:

#cartwin {

position: fixed;
z-index: 9999;
right: 0%;
top: 7%;
background-color: black;
border: 1px solid white;
border-radius: 5px;
height: 40%;
width: 25%;
visibility: hidden;
}

js:

cart.onclick = function togglecart() {

    const cart = document.getElementById('cartwin').style.visibility;


    if (cart == 'visible') {

        cart = 'hidden';

    }

    else if (cart == 'hidden') {

        cart = 'visible';

    }

}

这段代码根本没有任何效果,经过一番查看后我倾向于认为它与我的 if 测试有关,但我找不到任何结果。

最佳答案

您将不得不使用 window.getComputedStyle

查看代码内的注释,点击时查看控制台

var cart = document.querySelector('.cart');
var cartwin = document.getElementById('cartwin')

cart.onclick = function togglecart() {

    var style = window.getComputedStyle(cartwin);

    console.log(style.visibility);

    // use style.visibility
    // this is an option now you can handle 
    // what you have started with in your question
    // and move on from here with rest of your code

    // BUT before you do so, see the next snippet
    // on how much simpler you could achieve what I believe you are trying

}
#cartwin {

position: fixed;
z-index: 9999;
right: 0%;
top: 7%;
background-color: black;
border: 1px solid white;
border-radius: 5px;
height: 40%;
width: 25%;
visibility: hidden;
}
<div class="cart">click on cart here</div>
<div id="cartwin">
  <h4>lots of products in my cart</h4>
</div>

上面的例子是为了解决你所面临的问题并展示了一个可能的解决方案,但是......

将此代码段视为更好的解决方案 在这里您不会使用 javascript 处理样式,而只是通过 javascript 添加/删除一个类。

var cart = document.querySelector('.cart');
var cartwin = document.getElementById('cartwin')

cart.onclick = function togglecart() {

    // handle the logic here in javascript
    // but keep the styles where they belong => CSS
    // all you need to do here is "toggle" a class name
    cartwin.classList.toggle('active');

}
#cartwin {

position: fixed;
z-index: 9999;
right: 0%;
top: 7%;
background-color: black;
border: 1px solid white;
border-radius: 5px;
height: 40%;
width: 25%;
visibility: hidden;
}

#cartwin.active {
    visibility: visible;
}
<div class="cart">click on cart here</div>
<div id="cartwin">
  <h4>lots of products in my cart</h4>
</div>

关于javascript - 尝试获取样式元素时未获得正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55313113/

上一篇:php - PHP 代码中的选择标签与下一个 <h2> 标签重叠

下一篇:jquery - 工具提示超出屏幕

相关文章:

javascript - 如何正确地将 dragenter 应用于元素

javascript - 使用多个键过滤数组

javascript - 如何清除文件输入而不丢失事件监听器和扩展属性?

javascript - 如何隐藏该段落标签?

javascript - Bootstrap 字形图标/导航栏显示弹出窗口

css - 在 div 中设置背景图像,位置选项

html - 防止浏览器使用默认/后备字体

javascript - 如何使用 Javascript 更改悬停样式?

html - div 在另一个里面的位置

javascript - Mean.io 中奇怪的请求重复