繁体   English   中英

当另一个元素在视图中时,更改一个元素的 CSS

[英]Change CSS of one element when another element is in view

我正在创建一个 web 页面,其一侧有一个索引,并带有指向页面上每个相关部分的锚链接。

加载页面后,索引列表上的第一个点被突出显示(不同的颜色),当用户手动向下滚动到另一个部分时,我希望索引列表上的相应点随后被突出显示。

所以我有一个 CSS 属性,以突出显示索引点,这最初设置为列表中的第一个点。

如何从一个元素中获取此 CSS 属性,并将其提供给另一个元素?

.current {
    opacity: 1;
    -webkit-transition: opacity 200ms ease;
    transition: opacity 200ms ease;
  }

这是应用于应突出显示的元素的 CSS。 目前,索引中的第一个元素总是突出显示,但当然,我需要在用户向下滚动页面时更改它。

如果您需要更多信息,请告诉我。

可以使用Intersection Observer API

使用 jQuery 的示例代码:

$(window).scroll(function() {
  var scrollDistance = $(window).scrollTop();
  var threshold=250; //in px
  $('section').each(function(i) //list of sections tag to loop
  {
      if ($(this).position().top-threshold <= scrollDistance && i<4) {
          $('.nav-menu li.menu-active').removeClass('menu-active');
          $('.nav-menu li').eq(i).addClass('menu-active');
      }
  });
}).scroll();

您可以使用 onScroll 事件,以便在用户滚动时触发 function。 然后可以使用 scrollTop 来获取 position。

document.getElementById("idOfScrollingSection").onscroll(() => {
    let scrollValue = document.getElementById("elementId").scrollTop;
    
    //Remove class from highlighted item
    let oldElement = document.getElementsByClassName("current");
    oldElement.classList.remove("current");

    //Add highlight class, change values depending on page position
    if (scrollValue < 200) {
         let elementToBeHighlighted = document.getElementById("idOfElementToBeHighlighted");
         elementToBeHighlighted.classList.add("current");
    } else if ....

    } else {
         let elementToBeHighlighted = document.getElementById("idOfElementToBeHighlighted");
         elementToBeHighlighted.classList.add("current");
    }
    
})

这样做是纯 JS,使用 jQuery 会好很多

请看这个小提琴。 https://jsfiddle.net/cse_tushar/Dxtyu/141/

HTML:-

    <div class="m1 menu">
    <div id="menu-center">
        <ul>
            <li><a class="active" href="#home">Home</a>

            </li>
            <li><a href="#portfolio">Portfolio</a>

            </li>
            <li><a href="#about">About</a>

            </li>
            <li><a href="#contact">Contact</a>

            </li>
        </ul>
    </div>
</div>
<div id="home"></div>
<div id="portfolio"></div>
<div id="about"></div>
<div id="contact"></div>

CSS:-

    body, html {
    margin: 0;
    padding: 0;
    height: 100%;
    width: 100%;
}
.menu {
    width: 100%;
    height: 75px;
    background-color: rgba(0, 0, 0, 1);
    position: fixed;
    background-color:rgba(4, 180, 49, 0.6);
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
.light-menu {
    width: 100%;
    height: 75px;
    background-color: rgba(255, 255, 255, 1);
    position: fixed;
    background-color:rgba(4, 180, 49, 0.6);
    -webkit-transition: all 0.3s ease;
    -moz-transition: all 0.3s ease;
    -o-transition: all 0.3s ease;
    transition: all 0.3s ease;
}
#menu-center {
    width: 980px;
    height: 75px;
    margin: 0 auto;
}
#menu-center ul {
    margin: 15px 0 0 0;
}
#menu-center ul li {
    list-style: none;
    margin: 0 30px 0 0;
    display: inline;
}
.active {
    font-family:'Droid Sans', serif;
    font-size: 14px;
    color: #fff;
    text-decoration: none;
    line-height: 50px;
}
a {
    font-family:'Droid Sans', serif;
    font-size: 14px;
    color: black;
    text-decoration: none;
    line-height: 50px;
}
#home {
    background-color: grey;
    height: 100%;
    width: 100%;
    overflow: hidden;
    background-image: url(images/home-bg2.png);
}
#portfolio {
    background-image: url(images/portfolio-bg.png);
    height: 100%;
    width: 100%;
}
#about {
    background-color: blue;
    height: 100%;
    width: 100%;
}
#contact {
    background-color: red;
    height: 100%;
    width: 100%;
}

Jquery:-

 $(document).ready(function () {
    $(document).on("scroll", onScroll);
    
    //smoothscroll
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();
        $(document).off("scroll");
        
        $('a').each(function () {
            $(this).removeClass('active');
        })
        $(this).addClass('active');
      
        var target = this.hash,
            menu = target;
        $target = $(target);
        $('html, body').stop().animate({
            'scrollTop': $target.offset().top+2
        }, 500, 'swing', function () {
            window.location.hash = target;
            $(document).on("scroll", onScroll);
        });
    });
});

function onScroll(event){
    var scrollPos = $(document).scrollTop();
    $('#menu-center a').each(function () {
        var currLink = $(this);
        var refElement = $(currLink.attr("href"));
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
            $('#menu-center ul li a').removeClass("active");
            currLink.addClass("active");
        }
        else{
            currLink.removeClass("active");
        }
    });
}

请仅将活动的 class 添加到当前按钮(突出显示它)

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
/* Style the buttons */
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
  font-size: 18px;
}

/* Style the active class, and buttons on mouse-over */
.active, .btn:hover {
  background-color: #666;
  color: white;
}
</style>
</head>
<body>

<h1>Active Button</h1>
<p>Highlight the active/current (pressed) button.</p>
  
<div id="myDIV">
  <button class="btn">1</button>
  <button class="btn active">2</button>
  <button class="btn">3</button>
  <button class="btn">4</button>
  <button class="btn">5</button>
</div>

<script>
// Add active class to the current button (highlight it)
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
  var current = document.getElementsByClassName("active");
  current[0].className = current[0].className.replace(" active", "");
  this.className += " active";
  });
}
</script>

</body>
</html>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM