您的位置:首页 > Web前端 > JavaScript

Day-13 用js的dom操作实现图片切换

2016-01-05 23:21 183 查看
今天,用js实现了图片的切换效果,同时在网上找到了一种利用锚点实现的点击切换图片的方法

1、 用纯css实现图片切换

<!DOCTYPE html>
<head>
<title></title>
<meta charset="UTF-8" />
<style>
dl {   position:absolute;width:320px;height:240px;border:10px solid #eee;  }
dd {   margin:0;width:320px;height:240px;overflow:hidden;  }
img {     border:1px solid black   }
dt {   position:absolute;right:3px;top:50px;   }
a {     display:block;margin:1px;width:20px;height:20px;text-align:center;font:700 12px/20px "宋体",sans-serif;color:#fff;text-decoration:none;background:#666;border:1px solid #fff;filter:alpha(opacity=40);opacity:.4;   }
a:hover {background:#000}
</style>
</head>
<body>
<dl><dt><a href="#a" title="">1</a>
<a href="#b" title="">2</a>
<a href="#c" title="">3</a>
</dt>
<dd><img src="/images/m01.jpg" alt="" id="a" />
<img src="/images/m02.jpg" alt="" id="b" />
<img src="/images/m03.jpg" alt="" id="c" />
</dd>
</dl>
</body>
</html>


那么为什么这样就能实现图片的切换呢?

因为图片外面的大div定义了overflow:hidden,如果定义了overflow-y:scroll,就可以看到,里面的图片上下排列,当点击a链接时,滚动条会滚动到指定的图片上。

就好比你准备了一个1X1的画框,然后用一张1X3的纸条上面贴了3个图片,垂直拉来拉去的效果,画框外的遮掉了而已

2、用js实现鼠标划过按钮,切换图片

在实现此效果之前,我们要知道js的this变量。

首先分析this所在的函数是当做哪个对象的方法调用的,则该对象就是this所引用的对象。

var obj = {};

obj.x = 100;

obj.y = function(){ alert( this.x ); };

obj.y(); //弹出 100


这段代码中,this指向了obj对象,所以this.x返回的时obj的属性。

以下为用js实现的图片轮转

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
* {
margin:0;
padding:0;
}
.wai {
position: relative;
width: 500px;
margin: 100px auto 10px;
}

img {
display: none;
float: left;
}
#father li {
width: 15px;
height: 5px;
background-color: #ccc;
margin-left: 5px;
list-style-type: none;
float :left;
}
#father #first {
background-color: #f00;
}
#father {
width:80px;
height: 5px;
margin:0 auto;
}
#firstimg {
display: block;
}
.wai .clear {
clear:both;
}
</style>
</head>
<body>
<div class="wai">
<img id = "firstimg" src="images/1.jpg" alt="">
<div class="clear">
</div>
</div>
<ul id="father">
<li id="first"></li>
<li></li>
<li></li>
<li></li>
</ul>
<script>
var imgBox = document.getElementsByTagName('img');
var imgid = document.getElementById('firstimg');
var liBox = document.getElementsByTagName('li');
var i = 0;
for ( ;i < liBox.length; ) {
if(i!=0){
liBox[i].index = i;
liBox[i].onmouseover = function () {
this.style.background = '#f00';
imgid.src = 'images/'+ (this.index+1) +'.jpg';
liBox[0].style.background = '#ccc';
}
liBox[i].onmouseout = function () {
this.style.background = '#ccc';
}
}
else{
liBox[0].onmouseover = function () {
this.style.background = '#f00';
imgid.src = 'images/'+ (1) +'.jpg';
}
liBox[0].onmouseout = function () {
this.style.background = '#ccc';
}
}
i++;
};
</script>
</body>
</html>


当liBox[i].onmouseover时,因为不知道获取的是哪一个li的值,所以不能切换图片
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dom javascript 图片