Jquery背景图像上的淡入淡出也在淡入上面的句子



我想淡化不同的背景图像,但它也会影响上面的句子。

这里有一个简单的html测试:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link href="css/style.css" rel="stylesheet" />
<title>Title</title>
<script type="text/javascript" src="js/main.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<p id="myID">This sentence have a background who should <b> change ! </b><br><br><br><br><br><br><br><br>Yea...</p>
</body>
</html>

我已经做了一个类,有一组图像、id和索引,当它淡入/淡出时,它也会淡入文本。Js:

class changingImageObject {
constructor(img1, img2, img3, id) {
this.image = [img1, img2, img3];
this.id = id;
this.x = 0;
this.eraseBg = this.eraseBg.bind(this);
this.newBg = this.newBg.bind(this);
this.startTimer = this.startTimer.bind(this);
};
newBg() {
this.x = (this.x === 2) ? 0 : this.x + 1;
$(this.id).css('background-image', 'url(' + this.image[this.x] + ')');
$(this.id).fadeIn(1000); //this is new, will fade in smoothly
};
eraseBg() {
$(this.id).fadeOut(1000, this.newBg); //this is new, will fade out smoothly
};
startTimer() { //Change image after 3sec (looping)
setInterval(this.eraseBg, 3000);
};
}
const test = new changingImageObject("assets/img1.jpeg", "assets/img2.jpeg", "assets/img3.jpeg", '#myID');
test.startTimer();

Thx用于阅读。

Thansk to melancia我知道我需要使用rgba在不干扰孩子的情况下进行漂亮的淡出。这是代码:

class changingImageObject {
constructor(img1, img2, img3, id) {
this.erasing = false;                           //Boolean
this.op = 0.0;                                  //Opacité
this.image = [img1, img2, img3];                //Les images
this.id = id;                                   //L'id html
this.x = 0;                                     //L'index
this.eraseBg = this.eraseBg.bind(this);         //Les methods
this.newBg = this.newBg.bind(this);             //
this.startTimer = this.startTimer.bind(this);   //
this.changeBg = this.changeBg.bind(this);       //
};
newBg() {
if (this.op >= 1) { //If opacity is at 1 then change image and bring the opacity back to 0
this.erasing = true;
this.x = (this.x === 2) ? 0 : this.x + 1;
}
this.op += 0.01;
};
eraseBg() {
if (this.op <= 0) { //If opacity is at 0 then bring the opacity back to 1
this.erasing = false;
}
this.op -= 0.01;
};
changeBg() {
console.log(this.op);
if (this.erasing) this.eraseBg(); //If erasing then continue to erase
else this.newBg();                //If not continue to add opacity
$(this.id).css('background', 'rgba(0,0,0,' + this.op + ')');
$(this.id).css('background-image', 'url(' + this.image[this.x] + ')');
}
startTimer() { //Change image after 3sec (looping)
setInterval(this.changeBg, 30);
};
}
const test = new changingImageObject("assets/img1.jpeg", "assets/img2.jpeg", "assets/img3.jpeg", '#myID');
test.startTimer();

最新更新