我想让屏幕上的一些文字来回移动,目前我只能让文字从左到右移动。到目前为止,我将文本颜色设置为蓝色,它从一个方向移动到另一个方向,我尝试通过获取文本的位置然后将这些参数传递给我认为可以的另一个函数来使文本移回其原始位置让文字动起来。我试着改变了一些东西,最接近的是当文字看起来摇摇欲坠时,就好像它在试图移动一样。还有关于如何让文本经常改变颜色的想法吗?
感谢任何帮助!
var dom, x, y, finalx = 800, finaly = 0;
// ************************************************* //
// A function to initialize the x and y coordinates
// of the current position of the text to be moved,
// and then call the mover function
function initText() {
dom = document.getElementById('theText').style;
/* Get the current position of the text */
var x = dom.left;
var y = dom.top;
/* Convert the string values of left and top to
numbers by stripping off the units */
x = x.match(/\d+/);
y = y.match(/\d+/);
/* Call the function that moves it */
moveText(x,y);
/*** end of function initText */
}
// ************************************************* //
// A function to move the text from its original
// position to (finalx, finaly)
function moveText(x, y) {
if (x != finalx)
if (x > finalx) x--;
else if (x < finalx) x++;
if (y != finaly)
if (y > finaly) y--;
else if (y < finaly) y++;
if ((x != finalx) || (y != finaly)) {
dom.left = x + "px";
dom.top = y + "px";
setTimeout("moveText(" + x + "," + y + ")", 1);
initText2();
}
}
//Move text back to original position
function initText2(){
var dom2, x2,y2, finalx2=100, finaly2=0;
dom2 = document.getElementById('theText').style;
var x2 = dom2.left;
var y2 = dom2.top;
/* Convert the string values of left and top to
numbers by stripping off the units */
x2 = x2.match(/\d+/);
y2 = y2.match(/\d+/);
moveTextback(x2,y2);
}
function moveTextback(x2,y2){
if(x2!=finalx2)
if(x2>finalx2) x2--;
else if (x2<finalx2)x2++;
if(y2!=finaly2)
if(y2>finaly2)y2--;
else if(y2<finaly2)y2++;
if((x2!=finalx2) || (y2!=finaly2)){
dom2.style.left=finalx2+"px";
dom2.style.top=finaly2+"px";
setTimeout("moveText("+x2+","+y2+")",1);
}
}
<!DOCTYPE html>
<!-- moveText.html
Illustrates a moving text element
Uses the JavaScript from file moveText.js
-->
<html lang = "en">
<head>
<title> Moving text </title>
<meta charset = "utf-8" />
<style type = "text/css">
#theText {position: absolute; left: 100px; top: 100px;
font: bold 1.7em 'Times Roman';
color: blue;"> Save time with TIMESAVER 2.2;}
</style>
<script type = "text/javascript" src = "moveText.js">
</script>
</head>
<!-- Call the initializing function on load, giving the
destination coordinates for the text to be moved
-->
<body onload = "initText()">
<!-- The text to be moved -->
<p>
<span id = "theText"> Save time with TIMESAVER 2.2
</span>
</p>
</body>
</html>
最佳答案
只是CSS它....
span {
display: inline-block;
animation: weeee 6s linear infinite alternate;
}
@keyframes weeee {
0% { color: red; }
25% { color: blue; }
50% { color: green; }
75% { color: orange; }
100% { transform: translateX(101%); color: purple; }
}
<span>I AM SOME TEXT THAT MOVES BACK AND FORTH AND CHANGES COLORS AS IT GOES....WEEEEEEEE!</span>
关于javascript - 如何使文本在屏幕上来回移动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58867045/