我正在尝试在javascript中创建一个函数,该函数将增加单击的图像的大小。我不确定为什么不让我在javascript中使用rem,但是当我拿走rem时,数字本身仍然不起作用。

html:

<div class="main-textbox-about">
                    <div class="main-textbox-about-saints">
                        <img src="images/Saint Slide/st-peter-2176658_1280.jpg" class="main-textbox-about-saints-photos main-textbox-about-saints-photos-1" onclick="highlight();">
                        <img src="images/Saint Slide/saint-stylianos-2191792_1280.jpg" class="main-textbox-about-saints-photos main-textbox-about-saints-photos-2">
                        <img src="images/Saint Slide/st-demetrius-2176682_1280.jpg" class="main-textbox-about-saints-photos main-textbox-about-saints-photos-3">
                        <img src="images/Saint Slide/archon-2086750_1280.jpg" class="main-textbox-about-saints-photos main-textbox-about-saints-photos-4">
                        <img src="images/Saint Slide/st-andrew-2176673_1280.jpg" class="main-textbox-about-saints-photos main-textbox-about-saints-photos-5">
                        <img src="images/Saint Slide/saint-john-the-baptist-1652345_1280.jpg" class="main-textbox-about-saints-photos main-textbox-about-saints-photos-6">
                        <img src="images/Saint Slide/st-paul-2176669_1280.jpg" class="main-textbox-about-saints-photos main-textbox-about-saints-photos-7">
                    </div>
                </div>
function highlight() {
    var img = document.querySelector(".main-textbox-about-saints-photos")
    img.innerHTML.style.height = 50;
    img.innerHTML.style.width = 40;
}

最佳答案

您可以在图像的容器元素上添加单击侦听器,并使用事件对象获取被单击的图像并设置其宽度和高度。

width和height的值应该是字符串而不是数字

const imgContainer = document.querySelector('.main-textbox-about-saints');

imgContainer.addEventListener('click', (e) => {
  e.target.style.height = '150px';
  e.target.style.width = '150px';
});
<div class="main-textbox-about">
  <div class="main-textbox-about-saints">
    <img src="https://picsum.photos/100">
    <img src="https://picsum.photos/100">
    <img src="https://picsum.photos/100">
  </div>
</div>


编辑

根据您的评论,一次只需要一张大图片。您可以通过跟踪先前放大的图像并在发生单击事件时重置其宽度和高度来实现此目的

const imgContainer = document.querySelector('.main-textbox-about-saints');
let prevEnlargedImg;

imgContainer.addEventListener('click', (e) => {
  if (prevEnlargedImg) {
    prevEnlargedImg.style.height = '100px';
    prevEnlargedImg.style.width = '100px';
  }

  prevEnlargedImg = e.target;

  e.target.style.height = '150px';
  e.target.style.width = '150px';
});
<div class="main-textbox-about">
  <div class="main-textbox-about-saints">
    <img src="https://picsum.photos/100">
    <img src="https://picsum.photos/100">
    <img src="https://picsum.photos/100">
  </div>
</div>

09-16 22:18