簡體   English   中英

根據滾動更改進度條值

[英]Change Progress Bar Value based on Scrolling

我希望能夠根據我滾動的距離以及剩余的數量來增加我的進度條。

我試過這個: jsFiddle ,它似乎不起作用,我根據某人的腳本創建了一個腳本,使得一個塊基於scroll%水平移動。

我的代碼:

<progress id="progressbar" value="0" max="100"></progress>
<br />
<br />
<br />
Lorem<br />
Ipsum<br />
Dolor<br />
.
.
.
.

JS:

$(document).ready(function () {
    $(window).scroll(function () {
        var s = $(this).scrollTop(),
            d = $(document).height(),
            scrollPercent = (s / d);
        var position = (scrollPercent);
        $("#progressbar").progressbar('value', position);
    });
});

工作演示

試試這個

$(window).scroll(function () {
  var s = $(window).scrollTop(),
        d = $(document).height(),
        c = $(window).height();
        scrollPercent = (s / (d-c)) * 100;
        var position = scrollPercent;

   $("#progressbar").attr('value', position);

});

希望這有幫助,謝謝

邏輯是這樣的

totalValue  = (documentHeight - windowHeight);
currntValue = scrolledValue;
percentage =  (currntValue/ totalValue  ) * 100

http://jsfiddle.net/PvVdq/71/

   $(document).ready(function () {
    $(window).scroll(function () {
        var s = $(this).scrollTop(),
            d = $(document).height()-$(window).height(),
            scrollPercent = (s / d)*100;       
        $("#progressbar").attr('value', scrollPercent);
     });
 });

我建議根據頁面的大小使進度條的最大值動態化。

將進度條的HTML更改為此。

<progress id="progressbar" value="0"></progress>

這就是你的jQuery的外觀。

$(document).ready(function () {
    $(window).scroll(function () {
        var s = $(document).scrollTop(),
            d = $(document).height() - $(window).height();          
        $("#progressbar").attr('max', d);
        $("#progressbar").attr('value', s);
     });
 });

這消除了對hacky計算的需要,並且在頁面更長或更短的情況下使進度條動態化。

工作演示

要獲得當前的滾動比率,您應首先檢查文檔是否具有scrollableHeight。 在這個特殊情況下,我選擇返回0 下一次計算與上述相同。

/**
 * @returns number
 */
function scrollYProgression() {
    const scrollableHeight = window.document.body.scrollHeight - window.innerHeight;
    if (scrollableHeight <= 0) return 0;

    return window.scrollY / scrollableHeight;
}

捆綁了jQuery

$(window).scroll(() => {
    $('#progressbar')
        .attr('value', scrollYProgression() * 100);
});

當你聽滾動事件時要小心! 這可能非常沉重,每次重新繪制時最多需要一次。 您可以檢查window.requestAnimationFrame以防止大量調用您的方法(最多60 / s)。

關於滾動事件監聽器: http//www.html5rocks.com/en/tutorials/speed/animations

編輯

沒有jQuery並使用window.requestAnimationFrame將觸發率限制為60 / s

/** @return number */
function scrollYProgression() {
    const scrollableHeight = window.document.body.scrollHeight - window.innerHeight;
    if (scrollableHeight <= 0) return 0;

    return window.scrollY / scrollableHeight;
}

/**
 *  @return void
 *  @description DOM element manipulation
 */
function scrollHandler() {
    const progress = scrollYProgression();
    const bar = document.getElementById('progressbar');
    bar.setAttribute('value', progress * 100);
}

/** Start listening */
window.addEventListener('scroll', function(ev){
    window.requestAnimationFrame(scrollHandler);
}, { passive: true });

在現代網絡中,這可以在vanilla js中相當容易地完成(從本文中提取的基本方法):

 var progressBar = document.querySelector('progress'); var winheight, docheight, trackLength, throttlescroll; function getDocHeight() { var D = document; return Math.max( D.body.scrollHeight, D.documentElement.scrollHeight, D.body.offsetHeight, D.documentElement.offsetHeight, D.body.clientHeight, D.documentElement.clientHeight ); } function getMeasurements() { winheight = window.innerHeight || (document.documentElement || document.body).clientHeight; docheight = getDocHeight(); trackLength = docheight - winheight } function update() { var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop var pctScrolled = scrollTop / trackLength * 100; var wholePct = Math.floor(pctScrolled); progressBar.value = pctScrolled; } getMeasurements(); window.addEventListener('scroll', update, false); window.addEventListener("resize", getMeasurements, false); 
 progress { position: fixed; top: 0; left: 0; /* Reset the default appearance */ -webkit-appearance: none; appearance: none; } 
 <progress max="100"></progress> <p>Purr when being pet give me some of your food give me some of your food give me some of your food meh, i don't want it disappear for four days and return home with an expensive injury; bite the vet chew iPad power cord, but human give me attention meow or scream for no reason at 4 am. Lick sellotape hiss and stare at nothing then run suddenly away fall over dead (not really but gets sypathy) but sit in a box for hours, destroy the blinds. Meow all night having their mate disturbing sleeping humans and sometimes switches in french and say "miaou" just because well why not and pooping rainbow while flying in a toasted bread costume in space. Refuse to leave cardboard box eat from dog's food purr while eating. Leave hair everywhere lick master's hand at first then bite because im moody give attitude. </p> <p>Walk on car leaving trail of paw prints on hood and windshield attack the child so lick arm hair so relentlessly pursues moth, yet man running from cops stops to pet cats, goes to jail. Meow in empty rooms cough furball so give me some of your food give me some of your food give me some of your food meh, i don't want it fish i must find my red catnip fishy fish jumps off balcony gives owner dead mouse at present then poops in litter box snatches yarn and fights with dog cat chases laser then plays in grass finds tiny spot in cupboard and sleeps all day jumps in bathtub and meows when owner fills food dish the cat knocks over the food dish cat slides down the water slide and into pool and swims even though it does not like water pelt around the house and up and down stairs chasing phantoms so pee in the shoe. Munch, munch, chomp, chomp. Licks paws chase red laser dot or tuxedo cats always looking dapper meow i like frogs and 0 gravity or groom yourself 4 hours - checked, have your beauty sleep 18 hours - checked, be fabulous for the rest of the day - checked. Loves cheeseburgers. Toilet paper attack claws fluff everywhere meow miao french ciao litterbox play riveting piece on synthesizer keyboard put butt in owner's face step on your keyboard while you're gaming and then turn in a circle attack the dog then pretend like nothing happened. </p> 

但是,最好限制requestAnimationFrame運行滾動函數的數量,在這種情況下,它會更復雜一些:

 var progressBar = document.querySelector('progress'), ticking = false; var winheight, docheight, trackLength, throttlescroll; function getDocHeight() { var D = document; return Math.max( D.body.scrollHeight, D.documentElement.scrollHeight, D.body.offsetHeight, D.documentElement.offsetHeight, D.body.clientHeight, D.documentElement.clientHeight ); } function getMeasurements() { winheight = window.innerHeight || (document.documentElement || document.body).clientHeight; docheight = getDocHeight(); trackLength = docheight - winheight } function requestTick() { if(!ticking) { requestAnimationFrame(update); ticking = true; } } function update() { var scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop var pctScrolled = scrollTop / trackLength * 100; var wholePct = Math.floor(pctScrolled); progressBar.value = pctScrolled; ticking = false; } getMeasurements(); window.addEventListener('scroll', requestTick, false); window.addEventListener("resize", getMeasurements, false); 
 progress { position: fixed; top: 0; left: 0; /* Reset the default appearance */ -webkit-appearance: none; appearance: none; } 
 <progress max="100" value="0"></progress> <p>Purr when being pet give me some of your food give me some of your food give me some of your food meh, i don't want it disappear for four days and return home with an expensive injury; bite the vet chew iPad power cord, but human give me attention meow or scream for no reason at 4 am. Lick sellotape hiss and stare at nothing then run suddenly away fall over dead (not really but gets sypathy) but sit in a box for hours, destroy the blinds. Meow all night having their mate disturbing sleeping humans and sometimes switches in french and say "miaou" just because well why not and pooping rainbow while flying in a toasted bread costume in space. Refuse to leave cardboard box eat from dog's food purr while eating. Leave hair everywhere lick master's hand at first then bite because im moody give attitude. </p> <p>Walk on car leaving trail of paw prints on hood and windshield attack the child so lick arm hair so relentlessly pursues moth, yet man running from cops stops to pet cats, goes to jail. Meow in empty rooms cough furball so give me some of your food give me some of your food give me some of your food meh, i don't want it fish i must find my red catnip fishy fish jumps off balcony gives owner dead mouse at present then poops in litter box snatches yarn and fights with dog cat chases laser then plays in grass finds tiny spot in cupboard and sleeps all day jumps in bathtub and meows when owner fills food dish the cat knocks over the food dish cat slides down the water slide and into pool and swims even though it does not like water pelt around the house and up and down stairs chasing phantoms so pee in the shoe. Munch, munch, chomp, chomp. Licks paws chase red laser dot or tuxedo cats always looking dapper meow i like frogs and 0 gravity or groom yourself 4 hours - checked, have your beauty sleep 18 hours - checked, be fabulous for the rest of the day - checked. Loves cheeseburgers. Toilet paper attack claws fluff everywhere meow miao french ciao litterbox play riveting piece on synthesizer keyboard put butt in owner's face step on your keyboard while you're gaming and then turn in a circle attack the dog then pretend like nothing happened. </p> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM