在页面上悬停div时将样式添加到正文

时间:2015-05-06 14:52:20

标签: css

我知道我可以阻止页面滚动使用:

body {
    position: fixed;
    overflow: hidden;
}

但是当用户将鼠标悬停在我的页面上的div上时,我需要应用这些样式。

有没有办法将样式应用到这样的身体 - 从悬停内部?

2 个答案:

答案 0 :(得分:3)

无法使用CSS为父级设置样式,但您可以使用javascript。注意我已经为背景颜色添加了一条线以模拟效果,可以将其删除。



document.getElementById("hover").onmouseover = function() {
  // on hover set the body to position fixed and overflow hidden
  document.body.style.position = "fixed";
  document.body.style.overflow = "hidden";
  document.body.style.background = "rgba(0,75,250,0.5)";
}
document.getElementById("hover").onmouseout = function() {
  // when the user is done hovering, reset
  document.body.style.position = "";
  document.body.style.overflow = "";
  document.body.style.background = "";
}

<div id="hover">Hover over me</div>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

像这样(用jQuery完成):

<div>Test</div>

$('div').hover(function() {
    $('body').attr('position','fixed');
    $('body').attr('overflow','hidden');
});