我试图根据以前的状态将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测试有关,但经过一番环顾,但我什么都找不到。
答案 0 :(得分:1)
您将必须使用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>