走马灯
1. js方法
<style>
.second {
position: relative;
float: left;
width: 500px;
height: 30px;
margin: 20px 0 0 65px;
padding: 0 20px;
line-height: 28px;
background: #fdfdfd;
border: 1px solid #d6d6d6;
background-color: lightblue;
border-radius: 12px;
overflow: hidden;
}
div.second>div {
overflow: hidden;
cursor: pointer;
}
div.second>div>span {
display: inline-block;
}
</style>
</head>
<body>
<div class="second">
<div>
<span>这是一段文字,走马灯的效果,我们只有比别人更努力才能更好,做一名文艺的程序员好像也不错诶。</span>
</div>
</div>
</body>
<script>
var pp = document.querySelector('.second>div>span');
var x = 40;
var scroll = function () {
pp.style.marginLeft = x + 'px';//通过改变margin-left的值来写出走马灯的效果
x--;
if (x + pp.offsetWidth <= 0) {
x = 430; //根据最外层div标签的宽度来设置(上述宽度为500px)
}
}
setInterval(scroll, 20);
</script>
2.css方法
这个方法是我在网上看到别人写的,然后使用了一下发现也挺好用的,之前写小程序的时候用js方法写会有一些小bug,但是这个方法没有那些问题,相比较而言很稳定,如果你有更好的方法,欢迎来留言。
这里为了连续无限滚动,特意复制了2份跑马灯的内容(.content)。
<style>
@keyframes kf-marque-animation {
0% {
transform: translateX(10%);
}
100% {
transform: translateX(-33.3%);
}
}
.marquee {
width: 500px;
height: 44px;
line-height: 44px;
background: lightblue;
overflow: hidden;
white-space: nowrap;
text-overflow: clip;
/* position: relative; */
font-size: 14px;
}
.marquee .content {
display: inline-block;
/* position: relative; */
padding-right: 0px;
animation: kf-marque-animation 11.3s linear infinite;
white-space: nowrap;
}
</style>
</head>
<body>
<div>css3 + animation跑马灯</div>
<div class="marquee">
<div class="content">
<span>这是一段文字,走马灯的效果,我们只有比别人更努力才能更好,做一名文艺的程序员好像也不错诶。</span>
<span style="display: inline-block;width:5em"></span>
<span>这是一段文字,走马灯的效果,我们只有比别人更努力才能更好,做一名文艺的程序员好像也不错诶。</span>
<span style="display: inline-block;width:5em "></span>
<span>这是一段文字,走马灯的效果,我们只有比别人更努力才能更好,做一名文艺的程序员好像也不错诶。</span>
<span style="display: inline-block; width:5em"></span>
</div>
</div>
</body>