• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
前端露
博客园    首页    新随笔    联系   管理    订阅  订阅

js 图片滑动

var speed = 5;
var box = document.getElementById("scrollbox");
var picBox = document.getElementById("scrollpic");
var imgWidth = document.getElementById("pic").offsetWidth;
var direction = 'right';
slide(speed);
function slide(speed){
    var timer = setInterval(move,speed);
    box.onmouseover = function(){clearInterval(timer);};
    box.onmouseout = function(){timer = setInterval(move,speed);};
}
function changeDirection(){
    if(box.scrollLeft <= 0){
        direction = 'right';
    }
    if(picBox.offsetWidth - box.scrollLeft <= imgWidth){
        direction = 'left';
    }
}
function move(){
    changeDirection();
    switch(direction){
        case 'left': 
                box.scrollLeft--;
                break;
        case 'right':
                box.scrollLeft++;
                break;
        default:console.log('出错了');
    }
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>javascript图片上下无缝滚动</title>
<link rel="stylesheet" type='text/css' href='1.css'/>
</head>
<body>
<div id="scrollbox">
    <div id="scrollcon">
        <div id="scrollpic">
            <a href="javaScript:void(0)"><img src="images/1.jpg"  id="pic"/></a>
            <a href="javaScript:void(0)"><img src="images/2.jpg" /></a>
            <a href="javaScript:void(0)"><img src="images/3.jpg" /></a>
            <a href="javaScript:void(0)"><img src="images/4.jpg" /></a>
            <a href="javaScript:void(0)"><img src="images/5.jpg" /></a>
        </div> 
    </div>
</div>
<script src="1.js" type='text/javascript'></script>
</body>
</html>
*{
    margin:0;
    padding:0;
    border:0;
}
#scrollbox{
    background:#FFF;
    width:304px;
    height:304px;
    margin:10px auto;
    overflow: hidden;
}
#scrollcon{
    width:2000px;
    height:304px;
}
#scrollpic{
    width:1510px;/*每张图片宽度为300,加上每张图片margin-right为2,300*5+2*5=1510*/
    display: inline-block;/*去除浮动*/
    *display: inline;
    *zoom:1;
}
#scrollpic a{
    float: left;
    margin-right:2px; 
}
#scrollpic img{
    width: 300px;
    height: 300px;
}

下载地址:https://files.cnblogs.com/qduanlu/%E5%9B%BE%E7%89%87%E6%BB%91%E5%8A%A8.zip

posted @ 2012-12-23 20:54  前端露  阅读(397)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3