开发者

Is it possible to place a focus point on a page, so if content changes, the scroll bar moves with that point?

开发者 https://www.devze.com 2023-01-16 21:40 出处:网络
My question is pretty much as the title suggests, I have a message board which constantly expands and pushes messages down when new ones are开发者_运维问答 added. I want to be able to lock the scroll

My question is pretty much as the title suggests, I have a message board which constantly expands and pushes messages down when new ones are开发者_运维问答 added. I want to be able to lock the scroll to a message for example so the page scroll bar moves when the message board extends to keep the same view of messages that you had initially. Is this possible with jquery? Any advice appreciated.


You'll need to register a callback or event handler that gets triggered whenever the content on the page changes.

The you'll need a scroll-to function. Check out http://demos.flesler.com/jquery/scrollTo/.

...
// Insert this code where you are adding the message to the page
// New message, trigger the custom event callback
// Assumes 'message' is a jQuery object for the new message.
message.trigger('scroll-to-message');
...

jQuery(function() {
  // Bind a handler for all messages (which should have a class 'message')
  // with a custom event name
  jQuery(document).delegate('.message', 'scroll-to-message', function() {
    var message = jQuery(this);
    jQuery.scrollTo(message);
  });
});


In my answer, you just need to send and attribute telling the order of messages. In example below, will scroll to "Message Bar", then to "new message".

You can use this.

HTML

Messages:

<div id="board">
    <span class="message" order="2">Message Foo</span>
    <span class="message" order="3">Message Bar</span>
    <span class="message" order="1">Message Test</span>
</div>

JS

$(document).ready(function(){   
    // each half second, updates scroll
    window.setInterval(updateScroll, 100);    

    // after 2 seconds, add new message to test scroll
    window.setInterval(newMessage, 2000);             
});

// find message with bigger order number, and scroll to it
function updateScroll(){
    var messages = $(".message");
    var newMessage = $(messages[0]);
    $(".message").each(function(){
        if ($(this).attr("order") > $(newMessage).attr("order")) {
            newMessage = $(this);
        }
    });
    var top = newMessage.offset().top;
    $(document).scrollTop(top);    
}

function newMessage() {
    var text = Date() + "<br/> - new message!";
    var tag = "<span order=\"9\" class=\"message\">" + text + "</span>";
    $('#board').prepend(tag);
}

See in jsfiddle


EDIT

Explanations:

  • $(document).ready: after page loads
  • window.setInterval(updateScroll, 100);: calls updateScroll function each 0.1 seconds.
  • $(".message").each(function(){...}): get the position of element with bigger order
  • $(document).scrollTop(top): scrolls page to that position
0

精彩评论

暂无评论...
验证码 换一张
取 消