图片切换功能实现概述
许多网站的主界面都具备图片自动切换的功能,这种效果通常是如何实现的呢?
首先,我们需要构建如下的HTML页面布局结构。
|
Main(div)
bottom
| UL (li)<选择>left |
center |
right |
HTML页面布局与代码实现接下来,具体实现上述的页面布局。
参考文件 swap.html 中的代码结构。
<!DOCTYPE html PUBLIC '-//W3C//DTD HTML 4.01 Strict//EN' 'http://www.w3.org/TR/html4/strict.dtd'>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<title>在此插入标题</title>
<link rel="stylesheet" type="text/css" href="swap.css"/>
<script type="text/javascript">
<!--
function swap(val){
if(val=="left"){
left.style.display='block';//设置为显示
center.style.display='none';//设置为隐藏
right.style.display='none';
}else if(val=="center"){
left.style.display='none';
center.style.display='block';
right.style.display='none';
}else if(val=="right"){
left.style.display='none';
center.style.display='none';
right.style.display='block';
}
}
-->
</script>
</head>
<body>
<div class="main">
<div class="top">
<div class="left" id="left"><img src="images/left.jpg"/></div>
<div class="center" id="center"><img src="images/center.jpg"/></div>
<div class="right" id="right"><img src="images/right.jpg"/></div>
</div>
<div class="bottom">
<ul>
<li onmouseover="swap('left')"></li>
<li onmouseover="swap('center')"></li>
<li onmouseover="swap('right')"></li>
</ul>
</div>
</div>
</body>
</html>
CSS样式控制与注意事项此外,还需要通过CSS样式来完善视觉效果。
参考文件 swap.css 中的样式定义。
@CHARSET "UTF-8";
.main{
width:1320px;
height:334px;
border:1px solid red;
background-color:silver;
}
.top{
width:1300px;
height:304px;
margin-top: 5px;
margin-left: 10px;
background-color: green;
}
.top .left{
display: block;//让left.jpg作为第一张图片显示
}
.top .center{
display: none;//初始状态不显示
}
.top .right{
display: none;//不显示
}
.bottom{
width:1300px;
height:15px;
margin-top: 5px;
margin-left: 10px;
background-color: gray;
}
.bottom ul{
margin: 0px;
margin-left:500px;
padding: 0px;
width:260px;
height:50px;
}
.bottom ul li{
width:80px;
height:10px;
margin-top:3px;
margin-right:3px;
background-color:yellow;
list-style-type: none;
float:left;
}
在开发过程中,有几个关键点需要注意。
第一,需要明确 display 和 visibility 属性之间的区别。
当设置 display 为 none 时,元素不仅内容被隐藏,而且不再占据页面空间,相当于该元素从文档流中暂时移除,对当前页面布局不再产生任何影响。
当设置 visibility 为 hidden 时,虽然内容不可见,但元素仍然占据原有的页面空间并参与布局计算,相当于只是将内容隐藏而元素本身依然存在。通俗来说,这就像是“占着位置不干活”。
第二,需要区分是点击切换还是鼠标悬停切换,两者使用的函数不同。本文示例中,当鼠标移动到指定区域时即触发图片切换,因此使用的是 onmouseover() 事件。
以上便是利用 JavaScript 实现点击按钮后图片自动切换的完整方法,希望对大家有帮助。 | |