【问题标题】:How to change background color of the body element when on certain section Javascript? [duplicate]在某些部分 Javascript 上如何更改正文元素的背景颜色? [复制]
【发布时间】:2021-02-14 05:01:17
【问题描述】:

我想在用户向下滚动页面时更改背景颜色,所以它应该在部分更改时更改?我已经搜索过,但没有找到答案。

// When on particular section change body background-color 
const sectionOne = document.getElementById('section-1');
const sectionTwo = document.getElementById('section-2');
const sectionThree = document.getElementById('section-3');
const sectionFour = document.getElementById('section-4');

if(sectionOne) {
        document.body.style.backgroundColor = "#118AB2";   
    } else if (sectionTwo) {
        document.body.style.backgroundColor = "#06D6A0"; 
    } else if (sectionThree) {
        document.body.style.backgroundColor = "#FFD166"; 
    } else {
        document.body.style.backgroundColor = "#073B4C"; 
    }
section {
  height: 100vh;
}
<section id="section-1">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-2">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-3">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-4">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>

【问题讨论】:

  • 虽然这可能被认为是过度设计,但您可以使用Observer API。但是,如果您的部分总是填满整个页面,最简单的解决方案是使用 CSS 并将背景添加到部分本身。

标签: javascript html css


【解决方案1】:

有很多方法可以做到这一点。我会转向更动态的东西,比如这个示例代码。

基本上,颜色移动到data 属性&lt;section&gt;

您可以将颜色更改限制在段落而不是整个页面。

示例代码使用mouseover,但这可能不适合您。

function updateBG(e) {
  document.body.style.background = this.getAttribute("data");
}
window.onload = function(){
  var d = document.querySelectorAll("section[data]");
  if (d) {
    var i, max = d.length;
    for(i=0;i<max;i++) {
      d[i].addEventListener("mouseover",updateBG,false);
    }
  }
}
<section data="#118AB2">
<p>Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked.</p>
</section>
<section data="#06D6A0">
<p>Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked.</p>
</section>
<section data="#FFD166">
<p>Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked.</p>
</section>
<section data="#073B4C">
<p>Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked.</p>
</section>

【讨论】:

  • 谢谢!我已将它添加到我的代码中,并且效果很好。 :) 这太棒了。
【解决方案2】:

这是我使用 jquery 的解决方案。

$(document).scroll(function(event) {
  if ($(this).scrollTop() >= ($('#section-1').position().top - 100)) {
    $('body').css('background-color', '#118AB2');
  }
  if ($(this).scrollTop() >= ($('#section-2').position().top - 100)) {
    $('body').css('background-color', '#06D6A0');
  }
  if ($(this).scrollTop() >= ($('#section-3').position().top - 100)) {
    $('body').css('background-color', '#FFD166');
  }
  if ($(this).scrollTop() >= ($('#section-4').position().top - 100)) {
    $('body').css('background-color', '#073B4C');
  }
});
body {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  background-color: #118AB2;
  transition: .3s;
}

section {
  height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="section-1">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-2">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-3">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-4">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>

【讨论】:

  • 谢谢!我已经在我的代码中实现了它,并且它完美无缺。也是我在实践中进一步了解 JS 知识的一种方式。 :)
  • 总是乐于提供帮助:)
【解决方案3】:

这里是针对您在 Intersection Observer API 页面上给出的 Observable 示例的用例的快速改编。

let prevRatio = 0.0;
const sectionColors = {
  'section-1': 'rgba(17, 138, 178, ratio)',
  'section-2': 'rgba(6, 214, 160, ratio)',
  'section-3': 'rgba(255, 209, 102, ratio)',
  'section-4': 'rgba(7, 59, 76, ratio)'
}

function createObserver() {
  let observer;

  let options = {
    root: root,
    rootMargin: "0px",
    threshold: buildThresholdList()
  };

  observer = new IntersectionObserver(handleIntersect, options);
  observer.observe(sectionOne);
  observer.observe(sectionTwo);
  observer.observe(sectionThree);
  observer.observe(sectionFour);
}
  
function buildThresholdList() {
  let thresholds = [];
  let numSteps = 20;

  for (let i=1.0; i<=numSteps; i++) {
    let ratio = i/numSteps;
    thresholds.push(ratio);
  }

  thresholds.push(0);
  return thresholds;
}

function handleIntersect(entries, observer) {
  entries.forEach((entry) => {
    const id = entry.target.id;
    if (entry.intersectionRatio > prevRatio) {
      entry.target.style.backgroundColor = sectionColors[id].replace("ratio", entry.intersectionRatio);
    } else {
      entry.target.style.backgroundColor = sectionColors[id].replace("ratio", entry.intersectionRatio);
    }

    prevRatio = entry.intersectionRatio;
  });
}

let root = document.getElementById('snippet-result-code');
let sectionOne = document.getElementById('section-1');
let sectionTwo = document.getElementById('section-2');
let sectionThree = document.getElementById('section-3');
let sectionFour = document.getElementById('section-4');
createObserver();
html, body, p {
  margin: 0;
  padding: 0;
}

section {
  height: 100vh;
}
<section id="section-1">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-2">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-3">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>
<section id="section-4">
 <p> Bore hence worm impala glared much far amorally roadrunner held spluttered and mallard on this found yikes wild much began jeepers dear less excluding oh or oh goodness globefish gorilla crud gulped astride with thus the jellyfish inside mistook goodness correct unlocked rash one or conductively retrospectively beyond futile so where antelope oh knelt newt one dense and oversold hello boa the histrionically and soggy wow hello far this when.Oh cobra together impassively into the dear that regretful more leopard objective along sloth newt groaned as strived awkward imprecisely some athletic tiger lion hey boyishly up less stunningly pending stingy checked pushed crab outside yikes clenched fled around sanely hatchet dependently a heinous less some on pill hey repulsive wow quit mammoth swore then so far less doused up and scorpion dim hence jeepers at along upon forward scorpion sufficient next jeez cattily less mastodon blinked unlocked. <p>
</section>

【讨论】:

    猜你喜欢
    • 2019-10-31
    • 1970-01-01
    • 2020-02-11
    • 2011-04-29
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    • 2012-05-05
    相关资源
    最近更新 更多