[英]How can I change the style of an element when the classlist.add is on another element?
I want to change the size of an image when a button is clicked. 我想在单击按钮时更改图像的大小。 I have following code:
我有以下代码:
HTML: HTML:
<img id="pizzaImage" src="img/pizza.png" alt="pizza">
JS: JS:
var pizzaImage = document.getElementById('pizzaImage');
Button.onclick = function () {
pizzaImage.classList.add('changeSize');
};
CSS: (how the .changeSize should look like:) CSS :(。changeSize的外观应为:)
img {
width: 20%;
}
you could try this: 您可以尝试以下方法:
Button.onclick = function () {
var img= document.getElementById('yourImgId');
if(img && img.style) {
img.classList.add("newStyle");
}
};
the html for the image would be: 图像的html将是:
<img src="src" id="yourImgId"/>
Add this CSS as well: 也添加此CSS:
.newStyle {
width: 100px;
height: 200px;
}
classList.add() adds a class to the element. classList.add()将一个类添加到元素。 So
img.classList.add('changeSize');
所以
img.classList.add('changeSize');
adds the class changeSize
to the image that you have selected, making the HTML for it look something like: 将class
changeSize
添加到changeSize
的图像中,使其HTML如下所示:
<img src="URL" class="changeSize" />
To make the image grow bigger with that class, you can use the CSS selector img.changeSize
为了使图像在该类中变得更大,可以使用CSS选择器
img.changeSize
The final code could look something like this: 最终代码如下所示:
document.querySelector("#changeImgSizeBtn").addEventListener('click', function () { var img = document.querySelector("#imgID"); img.classList.add('changeSize'); });
img { max-width: 150px; } img.changeSize { max-width: 300px; }
<img src="https://i.imgur.com/FrVmtJl.jpg" alt="cat img" id="imgID" /> <br /> <button id="changeImgSizeBtn">Change image size</button>
Try adding a .changeSize class to your css: 尝试将.changeSize类添加到CSS中:
.changeSize {
width: 50%;
}
OR 要么
img.changeSize {
width: 50%;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.