首页 > 解决方案 > 如何在此代码中从左向右滑动文本而不是图像?

问题描述

我在这里有用于滑动图像的代码,但我想为滑动文本而不是图像做同样的事情,但是当我尝试它时它对我不起作用,所以任何人都可以为我做它从左到右移动的文本滑块没有鼠标点击的图像滑块?并提前感谢

 var mainImage = document.getElementById("mainImage");

//Create image array
var imageArray = ["Life is what happens to us while we are making other plans","Life is what happens to us while we are making other plans","Life is what happens to us while we are making other plans"];

//Set up array index
var imageIndex = 0;

function changeImage() {
    
    mainImage.setAttribute("src",imageArray[imageIndex]);
    imageIndex++;
    
    
    if(imageIndex >= imageArray.length) {
        
        imageIndex = 0;

      
}


    }



//Create function to cycle through images
mainImage.onclick = changeImage
   


//Call cycle function
var intervalHandle = setInterval(changeImage,3000);

mainImage.onclick = function () {
    clearInterval(intervalHandle);  
}
h1 {
            text-align: center;
        }
        #mainImage {

            padding-left: 350px;
            padding-top: 40px;
        }
//<img id="mainImage" src="images/D.png" />

标签: javascript

解决方案


你需要使用HTML DOM innerHTML Property.

创建一个有id="text"变化的元素document.getElementById("text").innerHTML

var textElement = document.getElementById("text");

//Create image array
var imageArray = ["Life is what happens to us while we are making other plans","Life is what happens to us while we are making other plans2","Life is what happens to us while we are making other plans3"];

//Set up array index
var imageIndex = 0;

function changeImage() {
    textElement.innerHTML = imageArray[imageIndex]
    imageIndex++;

    if(imageIndex >= imageArray.length) {
        imageIndex = 0;     
    }
}



//Create function to cycle through images
textElement.onclick = changeImage
   


//Call cycle function
var intervalHandle = setInterval(changeImage,3000);

textElement.onclick = function () {
    clearInterval(intervalHandle);  
}
h1 {
            text-align: center;
        }
        #mainImage {

            padding-left: 350px;
            padding-top: 40px;
        }
<p id="text"></p>


推荐阅读