开发者

unit of increment in scrollable areas / divs in javascript?

开发者 https://www.devze.com 2023-04-12 01:22 出处:网络
in javascript can I make sure that my large div开发者_如何学运维 scroll vertically only in chunks of(let\'s say) 16 pixels

in javascript can I make sure that my large div开发者_如何学运维 scroll vertically only in chunks of (let's say) 16 pixels

In java, those are called 'units of increment'.

I can't find anything similar in javascript: I want to ensure that a certain area (div) when partially scrolled is always a multiple of 16 the view.

That allows me to do tricks with background images and others.

thanks


var lastScroll = 0;
$('div').scroll(function(){
    var el = $(this),
        scroll = el.scrollTop(),
        round = lastScroll < scroll ? Math.ceil : Math.floor;
    lastScroll = round(scroll/16) * 16;
    el.scrollTop(lastScroll);
});

http://jsfiddle.net/m9DQR/2/

Ensures scrolls are done in multiples of 16 pixels. You can easily extend this to be a plugin that allows for a variable amount (not a fixed, magical 16).


Yes, this is possible, but it will require using javascript to capture the scroll event and then manipulate it. This script (sorry jQuery is what I had) and overrides the scroll event. It then replaces it with the exact same scroll distance. You could perform your own math to adjust the value of scrollTo. We have to check both mousewheel and DOMMouseScroll events because the first is not supported by FF. This doesn't seem to apply in your case, but a user may have the number of lines to scroll set to something other than the default three. So the if statement calculates the distance. I left it in there though in case other people stumble on this question and it is important to them though.

$('body').bind('mousewheel DOMMouseScroll', function(e) {
  var scrollTo = null;
  if (e.type == 'mousewheel') {
    scrollTo = (e.wheelDelta * -1);
  }
  else if (e.type == 'DOMMouseScroll') {
    scrollTo = 40 * e.detail;
  }
  //adjust value of scrollTo here if you like.
  scrollTo = 16;
  if (scrollTo) {
    e.preventDefault();
    $(this).scrollTop(scrollTo + $(this).scrollTop());
  }
});


Coming from another programming language I also found JavaScript difficult when dealing with UI. In your case I would just set a handler to the event onscroll and query the position of the div relative to the scroll position. Return false whenever position of div is not divisible by 16px and create a counter to allow reposition after another 16px is scrolled.

0

精彩评论

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