因为项目的原因,需要涉及到文字的左右的滚动,更早之前html发布<marqueen>标签可以同时支持文字可图片,但是实际效果是如果你的文字足够长的话,滚动间隙会存在比较大的白屏,而且浏览器的内存消耗也会剧增(实际体验会变卡),体验上并不能达打很好的效果,而且html5发布后,此项标签已经废弃,兼容性也有待考虑,所以根据需求,自己实现了文字和图片的滚动效果。相比与<marqueen>的简单调用来说,实现过程稍微有点繁琐,但还是能经得住考验。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style type="text/css">
h1 {
font: 400 16px/1 "Microsoft YaHei", KaiTi_GB2312, SimSun;
}
#marquee,
#marquee li {
position: relative;
margin: 0;
padding: 0;
width: 400px;
height: 40px;
list-style: none;
display: inline-block;
}
#marquee {
position: relative;
width: 200px;
height: 40px;
overflow: hidden;
border: 10px solid #c0c0c0;
white-space: nowrap;
}
#marquee a {
display: block;
padding: 5px;
text-decoration: none;
white-space: nowrap;
color: #000;
float: left;
}
</style>
<script>
/**
* @description: 元素无缝滚动方法
* @param {*} id 元素ID,页面唯一
* @return {*}
*/
var Marquee = function (id) {
var container = document.getElementById(id),
original = container.getElementsByTagName("li")[0],
options = arguments[1] || {},
speed = options.speed || 10, // 定义滚动速度
direction = options.direction || "left", // 定义滚动方向
field = "scrollLeft";
var clone = original.cloneNode(true); // 多复制一份滚动内容
container.appendChild(clone); // 插入到同级元素中
var rolling;
if (direction == "up") {
field = "scrollTop";
rolling = function () {
if (container[field] == clone.offsetTop) {
container[field] = 0;
} else {
container[field]++;
}
};
} else if (direction == "down") {
field = "scrollTop";
rolling = function () {
if (container[field] == 0) {
container[field] = clone.offsetTop;
} else {
container[field]--;
}
};
} else if (direction == "left") {
field = "scrollLeft";
rolling = function () {
if (container[field] == clone.offsetLeft) {
container[field] = 0;
} else {
container[field]++;
}
};
} else if (direction == "right") {
field = "scrollLeft";
rolling = function () {
if (container[field] == 0) {
container[field] = clone.offsetLeft;
} else {
container[field]--;
}
};
}
var timer = setInterval(rolling, speed); //设置定时器
container.onmouseover = function () {
clearInterval(timer);
}; //鼠标移到marquee上时,清除定时器,停止滚动
container.onmouseout = function () {
timer = setInterval(rolling, speed);
}; //鼠标移开时重设定时器
};
</script>
</head>
<body>
<h1>javascript无缝滚动</h1>
<ul id="marquee">
<li>
<a href="08/08/1541914.html">文字无缝滚动1</a>
<a href="09/02/1558998.html">文字无缝滚动2</a>
<a href="08/24/1552862.html">文字无缝滚动3</a>
<a href="09/14/1566157.html">文字无缝滚动4</a>
<a href="09/18/1568925.html">文字无缝滚动5</a>
<a href="08/13/1544365.html">文字无缝滚动6</a>
</li>
</ul>
<script>
Marquee("marquee", { speed: 20, direction: "left" });
</script>
</body>
</html>
默认是向左移动,如果需要向上或者向下则需要修改css
#marquee,
#marquee li {
position: relative;
margin: 0;
padding: 0;
width: 40px;
height: 200px;
list-style: none;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。