js实现图片推拉门效果代码实例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js实现图片推拉门效果代码实例

嘴角邪恶的弧线   2020-05-17 我要评论

初学者。

推拉门是网页中常见的一种形式,通过JS实现比较简单。主要是通过getElement找到节点元素,然后对其进行相应的赋值即可。

新建一个index.html文件,并在同一个目录中添加三个文件夹,images(用来当作“门”的图片),styles(用来存放css文件),scripts(用来存放js文件)。然后在index.html中添加代码:

<!doctype html>
<html>
	<head>
	<meta charset="utf-8"/>
	<title>sliding doors</title>
	<link rel="stylesheet" href="styleshttps://img.qb5200.com/download-x/doors.css" rel="external nofollow" />
	<script src="scriptshttps://img.qb5200.com/download-x/doors.js"></script>
	</head>
	<body>
		<div id="container">
			<img src="imageshttps://img.qb5200.com/download-x/door1.jpg" alt="柯南" title="柯南"/>
			<img src="imageshttps://img.qb5200.com/download-x/door2.jpg" alt="柯南" title="柯南"/>
			<img src="imageshttps://img.qb5200.com/download-x/door3.jpg" alt="柯南" title="柯南"/>
			<img src="imageshttps://img.qb5200.com/download-x/door4.jpg" alt="柯南" title="柯南"/>
		</div>
	</body>
</html>

接着是styles目录下的doors.css:

#container{
	height:600px;
	border-right:1px solid #ccc;
	border-bottom:1px solid #ccc;
	margin:0 auto;
	position:relative;
	overflow:hidden;
}
 
#container img{
	position:absolute;
	border-left:1px solid #ccc;
	display:block;
	left:0;
}

然后是scripts目录下的doors.js:

window.onload = function()
{
	var box = document.getElementById("container"); //获得容器对象
	var imgs = box.getElementsByTagName("img"); //获得图片对象数组
	imgWidth = imgs[0].offsetWidth; //图片宽度
	var exposeWidth = 100; //每张图片露出的宽度
	var boxWidth = imgWidth + exposeWidth * (imgs.length - 1);
	box.style.width = boxWidth + "px";
	
	//初始化图片位置
	function reset()
	{
		for(var i = 1; i < imgs.length; i ++)
		{
			imgs[i].style.left = imgWidth + (i - 1) * exposeWidth + "px";
		}
	} 
	reset();
	
	//开门时候每个图片应该左移的距离
	var translate = imgWidth - exposeWidth;
	//为每个图片添加事件
	for(var i = 0; i < imgs.length; i ++)
	{
		
		//自动执行函数
		(function(i){
			imgs[i].onmouseover = function()
			{
				//重置图片位置
				reset();
				for(var j = 1; j <= i; j ++)
				{
					imgs[j].style.left = parseInt(imgs[j].style.left, 10) - translate + "px";
					
				}
			};
			
		})(i);
	}
};

这样即可实现推拉门效果。

效果如下,截图略微粗糙

以上所述是小编给大家介绍的js实现图片推拉门效果代码实例详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们