【问题标题】:How to change body background image by hovering a li element如何通过悬停 li 元素来更改身体背景图像
【发布时间】:2015-10-10 18:29:38
【问题描述】:

我正在尝试完全按照该网站在主页上所做的操作:http://ingrupo.net.br/

当一个 li 元素悬停时,我需要更改我的身体背景图像,并且每个元素上也有不同的图像。

PS:没有必要,但如果有人可以像本网站一样帮助处理文本元素,我们将不胜感激。

【问题讨论】:

  • 您的网站未加载。
  • 老兄,这不是这里的工作方式,你必须在问题中展示你的研究,代码 sn-p 或类似 jsfiddle 的东西会很好
  • InsomniacSabbir 我在发布之前看到了这篇文章,但它对我不起作用。

标签: javascript jquery html css


【解决方案1】:

body {
    background-size: cover;
}
<script>
function myFunction2() {
    document.body.style.backgroundImage = "url('https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/Color_icon_red.svg/2000px-Color_icon_red.svg.png')";
}
</script>
<a href="link-to-where-you-want-to-go" onmouseover="myFunction2()">hello!</a>

这是您想要的示例,其中使用 css 设置背景样式。

【讨论】:

  • 这很好用。有什么方法可以通过 css 更自定义背景图像(控制大小、重复等)?
  • 当然!我编辑了我的回复,现在它包含一个如何设置背景样式的示例。如果您使用这样的js,甚至可以为不同的背景设置不同的样式:document.body.style.backgroundSize = "60px 120px"; inside myFunction2()
  • 非常感谢 Elliot,这对我有用。我只是想弄清楚如何在图像过渡中添加淡入淡出。
【解决方案2】:

试试这个https://jsfiddle.net/8k3kp6uu/

HTML

<div class="background-divs green active"></div>
<div class="background-divs blue"></div>
<div class="background-divs yellow"></div>

<ul class="links">
    <li><a class="link" data-background="green" href="">green</a></li>
    <li><a class="link" data-background="blue" href="">blue</a></li>
    <li><a class="link" data-background="yellow" href="">yellow</a></li>
</ul>

CSS

.background-divs {
    width: 100vw;
    height: 100vh;
    position: absolute;
    opacity: 0;
    top: 0;
    left: 0;
    right: 0;
    left: 0;
    visibility: visible;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

.background-divs.blue {
    background-color: blue;
}

.background-divs.green {
    background-color: green;
}

.background-divs.yellow {
    background-color: yellow;
}

.links {
    position: absolute;
    top: 0;
    left:0;
    z-index: 5;
}

.links  li {
    border: 1px solid white;
    color: white;
    margin: 30px 0;
    padding: 10px;
}

.active {
    opacity: 1;
    visibility: visible;
    -webkit-transition: all 0.5s ease;
    -moz-transition: all 0.5s ease;
    -o-transition: all 0.5s ease;
    transition: all 0.5s ease;
}

JS

$('.link').mouseover(function(e) {
e.preventDefault();
var color = $(this).attr('data-background');

$('.background-divs').removeClass('active');
$('.background-divs.'+color).addClass('active');

});

【讨论】:

  • 这太棒了内纳德。谢谢!效果很好。
  • 我很高兴能帮上忙 :)
猜你喜欢
  • 2012-08-10
  • 1970-01-01
  • 2012-12-02
  • 2022-01-18
  • 2015-12-16
  • 1970-01-01
  • 2020-07-24
  • 1970-01-01
  • 2013-11-02
相关资源
最近更新 更多