如何使用图像比较滑块比较两个图像
在这个项目中,我们将创建一个图像滑块,可以用它来检查两个图像是否完全相同。我们可以在垂直和水平方向上将第一个图像的每个边界与第二个图像进行比较。
步骤:
- 在HTML文件中创建一个主要的
div,然后我们在其中添加两个div,用于放置图像。 -
创建一个CSS文件,用于将图像添加到相应的
div中。 -
创建一个JavaScript文件,用于改变滑块的方向并比较两个图像。
HTML代码:
- 首先,创建一个HTML文件(index.html)。
- 在创建了我们的HTML文件之后,我们将使用
<title>标签为我们的网页设置标题。它应放置在<head>标签之间。 - 然后,我们将链接提供所有背景图像的CSS文件到我们的HTML中。这也要放置在
<head>标签之间。 - 接下来是我们HTML代码的主体部分。
- 首先,创建一个主要的div作为主盒子。
- 在该
div中,添加另外2个divs以添加图片1和图片2。 - 在body的末尾添加
<script>标签,将JavaScript文件与我们的HTML文件链接起来。
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>
PRESS:'v' for vertical movement & 'h' \
for horizontal movement
</h1>
<div class="main_box">
<div class="img1"></div>
<div class="img2"></div>
</div>
<script src="index.js"></script>
</body>
</html>
CSS代码: 以下是上述代码中使用的“style.css”文件的内容。CSS用于为我们的HTML页面提供不同类型的动画和效果,以使其对所有用户看起来具有交互性。请考虑以下几点。
- 还原所有浏览器效果。
- 使用类和id给HTML元素添加效果。
style.css
/* restoring all of the browser effects */
*{
margin: 0;
padding: 0;
box-sizing: border-box;
overflow: hidden;
}
/* same effects to the body */
body{
background-color: #000;
color: #fff;
}
/* positioning of heading */
h1{
display: flex;
justify-content: center;
}
/* positions of main div and 2 images */
.main_box,.img1,.img2{
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
.main_box{
margin-top: 2em;
margin-bottom: 2em;
}
.img1{
background-image: url(image-url);
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.img2{
background-image: URL(image-url);
background-size: cover;
background-position: center;
background-repeat: no-repeat;
left: 50%;
background-attachment: fixed;
border-top: solid red 5px;
border-left: solid red 5px;
}
JavaScript代码: 以下是我们编写的代码:
- 对于图像的移动,我们检测鼠标移动。
- 对于垂直和水平移动,我们使用不同键盘按键的事件监听器。
document.querySelector('css_selector')
=> returns the first element that matches with specified CSS selector.
垂直和水平运动指南
- 滑块的默认水平移动。
- 当用户按下 (v) 键一次时,垂直移动处于活跃状态。
- 当用户再次按下 (h) 键一次时,水平移动重新处于活跃状态。
注意: v和h只在特定情况下有效。
以下是上述HTML代码中使用的“index.js”文件的内容。
index.js
// calling all of the Html classes
const img2 = document.querySelector('.img2')
// horizontal movement
window.addEventListener('keydown',(e)=>{
if(e.key == 'h'){
window.addEventListener('mousemove',(e)=>{
img2.style.left = e.clientX +'px'
img2.style.top = 0 +'px'
})
}
})
// vertical movement
window.addEventListener('keydown',(e)=>{
if(e.key == 'v'){
window.addEventListener('mousemove',(e)=>{
img2.style.left = 0 +'px'
img2.style.top = e.clientY +'px'
})
}
})
// default movement of slider which is horizontal movement
window.addEventListener('mousemove',(e)=>{
img2.style.left = e.clientX + 'px'
img2.scroll.top = 0 + 'px'
})
输出: 通过这种方式,你可以将你的两张图片进行比较。

极客教程