js实现标题跑马灯功能,右移不能正常实现,没找到原因。。。

2020-09-12 01:10发布

问题:

代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ABCDEFGHIJKL</title>
<script type="text/javascript">
var direction = 'left';
onload = function () {
setInterval(function () {
var titleText, firstChar, others;
titleText = document.title;
if (direction = 'left') {
firstChar = titleText.charAt(0);
others = titleText.substring(1);
document.title = others + firstChar;
} else {
firstChar = titleText.charAt(title.length - 1);
others = titleText.substring(0, title.length - 1);
document.title = firstChar + others;
}
}, 200);
document.getElementById('btnr').onclick = function () {
direction = 'right';
};
document.getElementById('btnl').onclick = function(){
direction = 'left';
};
};
</script>
</head>
<body>
<input type="button" id="btnl" value="←" />
<input type="button" id="btnr" value="→" />
</body>
</html>

回答1:

在 js 里面判断的时候要用两个或者三个等号
一个等号是赋值的意思
另外你有一个未定义的变量 title

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>ABCDEFGHIJKL</title>
<script type="text/javascript">
var direction = 'left';
onload = function () {
setInterval(function () {
var titleText, firstChar, others;
titleText = document.title;
if (direction === 'left') {
firstChar = titleText.charAt(0);
others = titleText.substring(1);
document.title = others + firstChar;
} else {
firstChar = titleText.charAt(titleText.length - 1);
others = titleText.substring(0, titleText.length - 1);
document.title = firstChar + others;
}
}, 200);
document.getElementById('btnr').onclick = function () {
direction = 'right';
};
document.getElementById('btnl').onclick = function(){
direction = 'left';
};
};
</script>
</head>
<body>
<input type="button" id="btnl" value="←" />
<input type="button" id="btnr" value="→" />
</body>
</html>