我嘗試創建一個用于放大和縮小一些圖片的 javascript 類。但是頁面的所有圖片都會放大和縮小。我認為這是一個 javascript 回圈的問題,但我不能這樣做。這是我的班級,有人看到問題了嗎?
類影像{
constructor() {
this.ip = document.getElementsByClassName("image_petite");
this.images = [];
}
agrandir() {
for (let i=0; i < this.ip.length; i ) {
this.images.push(this.ip[i]);
};
console.log(this.images);
for (let j=0; j < this.images.length; j ) {
if (this.images[j].classList == "image_petite") {
this.images[j].classList.remove('image_petite');
this.images[j].classList.add('image_grande');
} else if (this.images[j].classList == "image_grande") {
this.images[j].classList.remove('image_grande');
this.images[j].classList.add('image_petite');
}
}
}
}
let image = new Image();
uj5u.com熱心網友回復:
this.images[j].classList == "image_petite"不是你如何檢查一個元素是否有一個類。相反,您使用contains:
if (this.images[j].classList.contains("image_petite")) {
// ...
}
不過,您單獨使用了一個回圈,它有意地處理this.images陣列中的所有內容。在不知道 DOM 結構(松散地,HTML)是什么樣子的情況下,很難說你應該做什么,但是如果你試圖調整一張影像的大小,你需要確定你想要調整大小的影像,這該代碼中沒有任何內容。
這是一個使用click處理程式的簡單示例:
顯示代碼片段
// This example uses event delegation
document.body.addEventListener("click", event => {
const image = event.target.closest("img");
if (image && event.currentTarget.contains(image)) {
// This is the image to enlarge or toggle
if (image.classList.contains("image_grand")) {
// Toggling it from big back to small
image.classList.remove("image_grand");
image.classList.add("image_petite");
} else {
// Making this the one big one
const big = document.querySelector(".image_grand");
if (big) {
// Make the current big one small again
big.classList.remove("image_grand");
big.classList.add("image_petite");
}
// Make this one big
image.classList.add("image_grand");
image.classList.remove("image_petite");
}
}
});
.image_petite {
width: 75px;
height: 75px;
}
.image_grand {
width: 150px;
height: 150px;
}
<div>
<img class="image_petite" src="https://via.placeholder.com/150/0000FF/808080 ?text=1">
</div>
<div>
<img class="image_petite" src="https://via.placeholder.com/150/0000FF/808080 ?text=2">
</div>
<div>
<img class="image_petite" src="https://via.placeholder.com/150/0000FF/808080 ?text=3">
</div>
也就是說,我想我只使用一個類并添加/洗掉該類,而不是兩個類。
uj5u.com熱心網友回復:
1000 謝謝你,你的代碼完美運行!
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/370037.html
標籤:javascript
上一篇:禁用周末和特定日期jQueryUIdatepicker
下一篇:無法驗證簽名ECDSA密鑰
