<分区>
标签 javascript css
<分区>
我正在尝试根据先前的状态将 div 元素的可见性设置为可见或隐藏。即,当元素之前可见时,我试图将可见性设置为隐藏,反之亦然。
<div id="cartwin"></div>
#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;
}
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/