0
当我将鼠标悬停在我的网站上的一个按钮上时,我正在淡入淡出我的背景图像。我能够获得背景图像以显示正确的属性,但我无法弄清楚如何淡入淡出(以使图像感觉平滑)以及如何淡入淡出所有的盒子那些目前正在盘旋。如果有任何建议,我可以得到它将不胜感激!如何使用JavaScript悬停背景图像?
Codepen:https://codepen.io/chriskaram/pen/ZXjjqj
网站:https://mydietgoal.com/mydietgoal-features-and-plans
document.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('btn1'),
outerContainer = document.getElementsByClassName('Main-content')[0];
var btnTwo = document.getElementById('btn2'),
outerContainer2 = document.getElementsByClassName('Main-content')[0];
var btnThree = document.getElementById('btn3'),
outerContainer3 = document.getElementsByClassName('Main-content')[0];
btn.addEventListener('mouseenter', hover);
btn.addEventListener('mouseleave', noHover);
btnTwo.addEventListener('mouseenter', hover2);
btnTwo.addEventListener('mouseleave', noHover2);
btnThree.addEventListener('mouseenter', hover3);
btnThree.addEventListener('mouseleave', noHover3);
function hover() {
outerContainer.style.backgroundImage = 'url(https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/59dbd720f5e2317170edb5bf/1507579681913/vegetables-fresh-healthy-food-my-diet-goal-hd.jpg)';
outerContainer.style.backgroundAttachment = "fixed";
outerContainer.style.backgroundPosition = "bottom";
outerContainer.style.backgroundRepeat = "no-repeat";
outerContainer.style.transition = "opacity .25s ease-in";
}
function hover2() {
outerContainer2.style.backgroundImage = 'url(https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/59dbd7358fd4d2e11c887fc1/1507579706733/deadlift-workout-compound-work-hard-my-diet-goal-hd.jpg)';
outerContainer.style.backgroundAttachment = "fixed";
outerContainer.style.backgroundPosition = "bottom";
outerContainer.style.backgroundRepeat = "no-repeat";
outerContainer.style.transition = "opacity .25s ease-in";
}
function hover3() {
outerContainer3.style.backgroundImage = 'url(https://static1.squarespace.com/static/59a7820e2994ca11766093d3/t/59dbd7514c0dbffb014a14c0/1507579730115/strong-powerful-motivation-healthy-body-my-diet-goal-hd.jpg)';
outerContainer.style.backgroundAttachment = "fixed";
outerContainer.style.backgroundPosition = "bottom";
outerContainer.style.backgroundRepeat = "no-repeat";
outerContainer.style.transition = "opacity .25s ease-in";
}
function noHover() {
outerContainer.style.backgroundImage = '';
}
function noHover2() {
outerContainer2.style.backgroundImage = '';
}
function noHover3() {
outerContainer3.style.backgroundImage = '';
}
});
“.Main-content”元素在哪里?在你的背景中找不到任何东西,所以当然没有任何东西可以设定。使用CSS而不是JS设置背景图像可能会更好,并且使用JS仅用于切换决定是否需要显示背景图像的类。 – Terry
更新了[CodePen](https://codepen.io/anon/pen/ZXjvrd),代码全部基于网站,我将一个工作样本导入笔中。道歉 –