JavaScript 如何放大和缩小图像 |
您所在的位置:网站首页 › erp系统页面怎么放大和缩小图片 › JavaScript 如何放大和缩小图像 |
JavaScript 如何放大和缩小图像
放大和缩小是图像的一个重要功能。通过放大,我们可以看到图像的每一个信息。也许,你可以同时按下’ctrl’和’+’键来放大你的浏览器,你可以看到所有的东西在浏览器窗口中看起来更大。 缩放功能对于阅读屏幕上的小文本也很有用。因此,放大和缩小可以有多种用例。在本教程中,我们将学习使用JavaScript来放大和缩小图像。 使用高度和宽度属性进行放大和缩小JavaScript允许我们改变图像的尺寸。这意味着我们可以用JavaScript改变图像的高度和宽度。要放大,我们可以增加图像的高度和宽度,而要缩小,我们可以减少图像的高度和宽度。 语法用户可以按照下面的语法来使用图像的高度和宽度属性来添加放大和缩小功能。 // Zoom In image.style.width = (width + 50) + "px"; image.style.height = (height + 50) + "px"; // zoom out image.style.width = (width - 50) + "px"; image.style.height = (height - 50) + "px";在上面的语法中,width和height是图片的当前宽度和高度,我们可以在JavaScript中获得。 例子1在下面的例子中,我们创建了放大和缩小的按钮。当用户按下放大和缩小按钮时,会分别调用ZoomIn()和ZoomOut()函数。 在ZoomIn()和ZoomOut()函数中,我们使用它的id获得图像,并使用ClientHeight和ClientWidth属性获得高度和宽度。之后,我们从当前的高度和宽度中添加或删除50,并为图像设置一个新的高度和宽度。 Using the height and width property of images to add zoom in and zoom out features in images using JavaScript Zoom IN Zoom Out let image = document.getElementById('image'); function ZoomIn() { let width = image.clientWidth; let height = image.clientHeight; image.style.width = (width + 50) + "px"; image.style.height = (height + 50) + "px"; } function ZoomOut() { let width = image.clientWidth; let height = image.clientHeight; image.style.width = (width - 50) + "px"; image.style.height = (height - 50) + "px"; } 例子2在这个例子中,我们接受用户输入的图像的新宽度和高度。我们接受用户输入的数字,并将该数字作为图像的高度和宽度。所以,用户可以设置图片的自定义高度和宽度。 Allowing users to set custom height and width property of images to add zoom in and zoom out features in images using JavaScript Zoom IN or Out let image = document.getElementById('image'); function ZoomInOROut() { let width = prompt("Enter the new width of the image ", 500); let height = prompt("Enter the new height of the image", 500); image.style.width = width + "px"; image.style.height = height + "px"; } 例3在下面的例子中,我们为窗口中的按键事件添加了事件监听器。只要用户按下任何一个键,该事件就会触发,事件监听器将调用回调函数。 在事件监听器函数中,我们检查如果按下的键是’p’,我们将图像的高度和宽度增加100px,如果用户按下键’q’,我们将图像的高度减少100px。 Allowing users to set custom height and width property of images to add zoom in and zoom out features in images using JavaScript Press p for zoom in and q for zoom out let image = document.getElementById('image'); // add keypress event listener on window window.addEventListener('keypress', (event) => { // get the width and height of the image let width = image.clientWidth; let height = image.clientHeight; // when the user presses the 'p' key, zoom in if (event.key == 'p') { image.style.width = (width + 100) + "px"; image.style.height = (height + 100) + "px"; } // zoom out when the user presses the q key if (event.key == "q") { image.style.width = (width - 100) + "px"; image.style.height = (height - 100) + "px"; } })我们已经看到了三个使用JavaScript来放大和缩小图像的例子。要放大和缩小,我们只需要改变目标图像的宽度和高度。在最后一个例子中,我们已经看到了如何使用按键事件来放大和缩小。 |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |