Always scroll a div element and not page itself

核能气质少年 提交于 2019-12-01 03:21:19

I don't think that is possible to achieve without scripting it, which could be messy, considering the numerous events which scroll an element (click, scrollwheel, down arrow, space bar).

An option could be using the jQuery scroll plugin. I know it has the availability to create scrollbars on an div. The only thing you need to add yourself is the logic to catch the events when keyboard buttons are pressed. Just check out the keycodes for the arrow keys and make the div scroll down.

The plugin can be found here.

You can use it like this;

<script type="text/javascript">
  // append scrollbar to all DOM nodes with class css-scrollbar
  $(function(){
    $('.css-scrollbar').scrollbar();
  })
</script>

here is a solution that might work: (fiddle: http://jsfiddle.net/maniator/9sb2a/)

var last_scroll = -1;
$(window).scroll(function(e){
    if($('#content').scrollTop());
    var scroll = $('#view').data('scroll');
    if(scroll == undefined){
        $('#content').data('scroll', 5);
        scroll = $('#content').data('scroll');
    }
    else {
        $('#content').data('scroll', scroll + 5);
        scroll = $('#view').data('scroll');
    }
    /*
    console.log({
        'window scroll':$('window').scrollTop(), 
        'scroll var': scroll, 
        'view scroll':$('#view').scrollTop(),
        'view height':$('#view').height(),
        'ls': last_scroll 
    });
    //*/
    if(last_scroll != $('#content').scrollTop()){ //check for new scroll
        last_scroll = $('#content').scrollTop()
        $('#content').scrollTop($('#content').scrollTop() + scroll);

        $(this).scrollTop(0);
        //console.log(e, 'scrolling');
    }

})

It is a bit buggy but it is a start :-)

The only way I believe you can achieve this is through the use of frames.

Frames - W3Schools Reference

If you just want to have a fixed positioned "div" and scroll only it, maybe you could use a trick like:

http://jsfiddle.net/3cpvT/

Scrolling with mouse wheel and all kinds of keys works as expected. Only thing is that the scrollbar is on the document body only.

I found a solution... Not perfect... http://jsfiddle.net/fGjUD/6/.

CSS:

body.noscroll {
    position: fixed;
    overflow-y: scroll;
    width: 100%;
}

JS (jQuery):

if ($("body").height() > $(window).height()) {
    var top;
    $('#scrolldiv').mouseenter(function() {
        top = $(window).scrollTop();
        $('body').addClass('noscroll').css({top: -top + 'px'});
    }).mouseleave(function() {
        $('body').removeClass('noscroll');
        $(window).scrollTop(top);
    });
}

The text wrapping problem can be solved putting the whole content in fixed-width div. There is another bug for IE browser. If the page has center-aligned backgrond, it will move left-right on mouseenter on #scrolldiv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!