嘿,我正在尝试使div上的点击变大,如果点击再次变小,我只是想知道是否有办法做到这一点?我可以在其中添加动画吗?
document.addEventListener('click', function(event) {
if (!event.target.matches('.hud-map')) return;
event.preventDefault();
var map = document.getElementById("hud-map");
map.style.height = "200px";
map.style.width = "200px";
}, false);
<div id="hud-map" class="hud-map" style="width: 100px; height: 100px;
border-radius: 1em; color: rgb(211, 84, 0); border: 2px solid rgb(0, 0, 0);">
</div>
对不起我的英语不好
答案 0 :(得分:1)
您可以使用CSS处理transition: all .5s;
之类的动画,并处理尺寸的切换,(map.style.height == '200px') ? "100px" : "200px";
之类的三元条件
document.addEventListener('click', function(event) {
if (!event.target.matches('.hud-map')) return;
event.preventDefault();
var map = document.getElementById("hud-map");
map.style.height = (map.style.height == '200px') ? "100px" : "200px";
map.style.width = (map.style.width == '200px') ? "100px" : "200px";
}, false);
#hud-map {
width: 100px;
height: 100px;
border-radius: 1em;
color: rgb(211, 84, 0);
border: 2px solid rgb(0, 0, 0);
transition: all .5s;
}
<div id="hud-map" class="hud-map">
</div>
答案 1 :(得分:0)
您应该执行以下操作,对于动画,只需将transition
添加到元素中即可。
document.addEventListener('click', function(event) {
if (!event.target.matches('.hud-map')) return;
event.preventDefault();
var map = document.getElementById("hud-map");
if (map.style.width === '200px') {
map.style.height = "100px";
map.style.width = "100px";
} else {
map.style.height = "200px";
map.style.width = "200px";
}
}, false);
<div id="hud-map" class="hud-map" style="width: 100px; height: 100px;
border-radius: 1em; color: rgb(211, 84, 0); border: 2px solid rgb(0, 0, 0);transition: all 200ms ease;">
</div>
答案 2 :(得分:0)
var isClicked = false;
document.addEventListener('click', function(event) {
if (!event.target.matches('.hud-map')) return;
event.preventDefault();
var map = document.getElementById("hud-map");
map.style.width = (isClicked ? 100 : 200) + 'px';
map.style.height = (isClicked ? 100 : 200) + 'px';
isClicked = isClicked ? false : true;
}, false);
<div id="hud-map" class="hud-map" style="width: 100px; height: 100px;
border-radius: 1em; color: rgb(211, 84, 0); border: 2px solid rgb(0, 0, 0);">
</div>
答案 3 :(得分:0)
只需切换一个类并使用css过渡为大小变化设置动画
document.querySelector('.map').addEventListener('click', function () {
this.classList.toggle('large')
})
div.map {
width: 100px;
height: 100px;
background-color: green;
transition: width 1s, height 1s;
}
div.map.large {
width: 300px;
height: 300px;
}
<div class="map"></div>