用js实现两个按钮控制两张图片,点击左侧按钮,第一张图往右走,点击右侧按钮,第二张图往左走
时间: 2023-08-29 20:04:22 浏览: 98
可以使用JavaScript中的DOM操作来实现这个功能,具体实现步骤如下:
1. HTML结构中需要包含两个按钮和两张图片:
```html
<div>
<button id="left-btn">左</button>
<img id="img1" src="path/to/image1.jpg" alt="image1">
<img id="img2" src="path/to/image2.jpg" alt="image2">
<button id="right-btn">右</button>
</div>
```
2. CSS样式中需要设置图片的定位方式为绝对定位,并且设置初始的left值:
```css
img {
position: absolute;
left: 0;
}
```
3. JavaScript中需要获取到左右按钮和两张图片的DOM元素,并且为按钮添加点击事件监听器:
```javascript
var leftBtn = document.getElementById('left-btn');
var rightBtn = document.getElementById('right-btn');
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
leftBtn.addEventListener('click', function() {
img1.style.left = parseInt(img1.style.left) + 10 + 'px';
});
rightBtn.addEventListener('click', function() {
img2.style.left = parseInt(img2.style.left) - 10 + 'px';
});
```
4. 在点击事件监听器中,修改图片的left值即可实现图片的移动效果。
完整代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图片移动</title>
<style>
img {
position: absolute;
left: 0;
}
</style>
</head>
<body>
<div>
<button id="left-btn">左</button>
<img id="img1" src="path/to/image1.jpg" alt="image1">
<img id="img2" src="path/to/image2.jpg" alt="image2">
<button id="right-btn">右</button>
</div>
<script>
var leftBtn = document.getElementById('left-btn');
var rightBtn = document.getElementById('right-btn');
var img1 = document.getElementById('img1');
var img2 = document.getElementById('img2');
leftBtn.addEventListener('click', function() {
img1.style.left = parseInt(img1.style.left) + 10 + 'px';
});
rightBtn.addEventListener('click', function() {
img2.style.left = parseInt(img2.style.left) - 10 + 'px';
});
</script>
</body>
</html>
```
阅读全文