javascript - 使用 Javascript 放大图像

标签 javascript html

我必须通过单击加号按钮将图像放大 20 像素,然后单击减号按钮将图像缩小 20 像素。图片宽度最大为 500px,最小宽度为 250px。

<div id="doc">
  <div id="buttons">
    <button id="plus" onclick="imagePlus()">+</button>
    <button id="moins" onclick="imageMinus()">-</button>
  </div>
  <img id="sun" src="images/soleil.jpg" alt="soleil" />
</div>

我尝试使用clientWidth来获取图像的当前宽度并增加它,但似乎不起作用

var imagePlus = function() {
    var img = document.getElementById("sun");
    var currWidth = img.clientWidth;
    if(currWidth == 500){
        null
    } else{
        img.style.width = (currWidth + 20) + "px";
    }
}

var imageMinus = function() {
    var img = document.getElementById("sun");
    var currWidth = img.clientWidth;
    if(currWidth == 250){
        null
    } else{
        img.style.width = (currWidth - 20) + "px";
    }
}

最佳答案

您需要通过这种方式为加号和减号按钮添加事件监听器,或者您也可以在加号和减号按钮上添加onclick事件。

const imagePlus = function () {
  var img = document.getElementById("sun");
  var currWidth = img.clientWidth;
  if (currWidth == 500) {
    null;
  } else {
    img.style.width = currWidth + 20 + "px";
  }
};

const imageMinus = function () {
  var img = document.getElementById("sun");
  var currWidth = img.clientWidth;
  if (currWidth == 250) {
    null;
  } else {
    img.style.width = currWidth - 20 + "px";
  }
};

document.querySelector("#plus").addEventListener("click", imagePlus);
document.querySelector("#minus").addEventListener("click", imageMinus);

关于javascript - 使用 Javascript 放大图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71458956/

相关文章:

javascript - redis.exceptions.ResponseError : MOVED error in redis set operation 错误

下载文件的javascript按钮

javascript - 为什么 fusionMap.js 插件会改变 Google map 的起始位置?

javascript - JQuery - 无法动态添加 SELECT 选项

php - CSS 未加载到移动版 Safari

javascript - css 中类内的目标类

javascript - 如何在 Angular 8 中使用来自 HTML 输入的 JSON 文件?

javascript - 提取 css 并与数据属性匹配

html - Swift 打开带参数的本地 HTML 文件

javascript - 从数组中获取值并检查(勾选)相关复选框