如何使图像放大点击只使用javascript?



我正在学习一门课程,该课程要求本单元的所有工作都只能用Javascript完成。我的目标是使图像在我的网站的图片库放大时点击。问题是,onload事件似乎无法将事件侦听器添加到图像中。您可能会发现其他错误,但我想不出有任何其他问题可能会阻止代码运行。这是我得到的:

var imgList = document.getElementsByTagName("IMG");
var btn = document.getElementByClassName("reset-btn");
function enlargeImg(img) {
img.style.transform = "scale(1.5)";
img.style.transition = "transform 0.25s ease";
btn.style.visibility = "visible";
btn.addEventListener("click", resetImg);
}
function resetImg(img) {
img.style.transform = "scale(1)";
img.style.transition = "transform 0.25s ease";
}
function init() {
for (var i = 0; i < imgList.length; i++) {
var img = imgList[i];
img.addEventListener("click", enlargeImg);
}

} 
body.addEventListener("load", init);

我稍微重构了一下。我使用事件委托将click事件添加到整个主体中,然后使用target属性。

var imgList = document.querySelectorAll('img');
var btn = document.querySelector('.reset-btn');
var body = document.querySelector('body');

body.addEventListener("click", function(e){
enlargeImg(e);
});
btn.addEventListener('click' , resetImg);
function enlargeImg(e) {
let target = e.target;
if(target.className === 'img'){
target.style.transform = "scale(1.5)";
target.style.transition = "transform 0.25s ease";

}
}
function resetImg() {
for (let i of imgList){
i.style.transform = "scale(1)";
i.style.transition = "transform 0.25s ease";
}
}
.reset-btn {
margin-top: 200px;
}
<body>


<img class="img" src="https://images.unsplash.com/photo-1570824104453-508955ab713e?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=613&q=80">
<img class="img" src="https://images.unsplash.com/photo-1557246565-8a3d3ab5d7f6?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80">
<div>
<button class="reset-btn">Reset</button>
</div>

<script type="text/javascript" src="Answer boiler.js"></script>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<!-- <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script> -->
</body>

相关内容

  • 没有找到相关文章

最新更新