35

如何使用鼠标滚轮在 na div 中水平滚动,或使用 jquery 拖动?


我试过可拖动,但在我的代码中它没有用。

现在我有一个水平滚动条。是否可以使用鼠标滚轮滚动 div 中的内容?

4

8 回答 8

79

尝试使用鼠标滚轮进行水平滚动。这是纯 JavaScript:

(function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        document.getElementById('yourDiv').scrollLeft -= (delta * 40); // Multiplied by 40
        e.preventDefault();
    }
    if (document.getElementById('yourDiv').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('yourDiv').addEventListener('mousewheel', scrollHorizontally, false);
        // Firefox
        document.getElementById('yourDiv').addEventListener('DOMMouseScroll', scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('yourDiv').attachEvent('onmousewheel', scrollHorizontally);
    }
})();

这是一个演示,但带有document.bodywindow作为目标元素:https ://taufik-nurrohman.github.io/dte-project/full-page-horizo​​ntal-scrolling.html

于 2013-03-11T16:43:01.357 回答
19

我已经根据@Anonymous-Lettuce 的答案重写了代码。元素的宽度重新计算被跳过,因为它是不必要的,有时是不可取的。这还提供了传递给插件的scroll-amount附加功能。px

像这样使用它:

$(document).ready(function(){
    $('#your_div').hScroll(100); // You can pass (optionally) scrolling amount
});

这是升级的插件jquery.hscroll.js

jQuery(function ($) {
    $.fn.hScroll = function (amount) {
        amount = amount || 120;
        $(this).bind("DOMMouseScroll mousewheel", function (event) {
            var oEvent = event.originalEvent, 
                direction = oEvent.detail ? oEvent.detail * -amount : oEvent.wheelDelta, 
                position = $(this).scrollLeft();
            position += direction > 0 ? -amount : amount;
            $(this).scrollLeft(position);
            event.preventDefault();
        })
    };
});

这是相同的缩小版本jquery.hscroll.min.js

jQuery(function(e){e.fn.hScroll=function(l){l=l||120,e(this).bind("DOMMouseScroll mousewheel",function(t){var i=t.originalEvent,n=i.detail?i.detail*-l:i.wheelDelta,o=e(this).scrollLeft();o+=n>0?-l:l,e(this).scrollLeft(o),t.preventDefault()})}});

这是JSFiddle

于 2015-07-21T07:05:30.657 回答
6

几天前写了这个插件。

 $.fn.hScroll = function( options )
 {
   function scroll( obj, e )
   {
     var evt = e.originalEvent;
     var direction = evt.detail ? evt.detail * (-120) : evt.wheelDelta;

     if( direction > 0)
     {
        direction =  $(obj).scrollLeft() - 120;
     }
     else
     {
        direction = $(obj).scrollLeft() + 120;
     }

     $(obj).scrollLeft( direction );

     e.preventDefault();
   }

   $(this).width( $(this).find('div').width() );

   $(this).bind('DOMMouseScroll mousewheel', function( e )
   {
    scroll( this, e );
   });
}

试试看

$(document).ready(function(){
     $('#yourDiv').hScroll();
});

div的子元素的宽度应该比父元素宽。

比如 4000 像素什么的。

 <div id="yourDiv">
       <div style="width: 4000px;"></div>
 </div>
于 2013-02-26T11:22:49.810 回答
5

我想对@Taufik 给出的答案稍加改进。

es2015模块的上下文中:

const el = document.querySelector('#scroller');

function scrollHorizontally(e) {
  e = window.event || e;
  e.preventDefault();
  el.scrollLeft -= (e.wheelDelta || -e.detail);
}

function init() {
  if (!el) {
    return;
  }

  if (el.addEventListener) {
    el.addEventListener('mousewheel', scrollHorizontally, false);
    el.addEventListener('DOMMouseScroll', scrollHorizontally, false);
  } else {
    el.attachEvent('onmousewheel', scrollHorizontally);
  }
}

export default init;

主要区别在于:el.scrollLeft -= (e.wheelDelta || -e.detail);

e.wheelData直接在滚动偏移量中使用意味着我们可以拥有惯性,使滚动可以逐渐减慢。我发现这对我很有效。

像这样在你的代码中使用(假设上面的代码在一个名为scroller.js的文件中):

import scroller from './scroller.js';
scroller();
于 2017-08-31T16:32:03.197 回答
4

您可以只使用 javascrpt(没有 Jquery)以一种清晰的方式做到这一点,并且还允许垂直滚动:

const target = document.querySelector('div')

target.addEventListener('wheel', event => {
  const toLeft  = event.deltaY < 0 && target.scrollLeft > 0
  const toRight = event.deltaY > 0 && target.scrollLeft < target.scrollWidth - target.clientWidth

  if (toLeft || toRight) {
    event.preventDefault()
    target.scrollLeft += event.deltaY
  }
})
于 2020-05-21T08:24:59.877 回答
2

CSS溶液

您不需要JavascriptJQuery为此
有关更多信息:https ://css-tricks.com/pure-css-horizo​​ntal-scrolling/

::-webkit-scrollbar {
  width: 1px;
  height: 1px;
}

::-webkit-scrollbar-button {
  width: 1px;
  height: 1px;
}

body {
  background: #111;
}

div {
  box-sizing: border-box;
}

.horizontal-scroll-wrapper {
  position: absolute;
  display: block;
  top: 0;
  left: 0;
  width: calc(250px + 1px);
  max-height: 750px;
  margin: 0;
  padding-top: 1px;
  background: #abc;
  overflow-y: auto;
  overflow-x: hidden;
  -webkit-transform: rotate(-90deg) translateY(-250px);
          transform: rotate(-90deg) translateY(-250px);
  -webkit-transform-origin: right top;
          transform-origin: right top;
}
.horizontal-scroll-wrapper > div {
  display: block;
  padding: 5px;
  background: #cab;
  -webkit-transform: rotate(90deg);
          transform: rotate(90deg);
  -webkit-transform-origin: right top;
          transform-origin: right top;
}

.squares {
  padding: 250px 0 0 0;
}
.squares > div {
  width: 250px;
  height: 250px;
  margin: 10px 0;
}
<div class="horizontal-scroll-wrapper squares">
  <div>item 1</div>
  <div>item 2</div>
  <div>item 3</div>
  <div>item 4</div>
  <div>item 5</div>
  <div>item 6</div>
  <div>item 7</div>
  <div>item 8</div>
</div>

于 2020-10-26T15:20:56.660 回答
0

在我的情况下,我需要在调整浏览器大小时将滚动重置为正常,所以我稍微修改了Izhar 的代码以使其适用于我的应用程序:

在浏览器调整大小时启动 hScroll:

$(function () {
     $(window).resize($('.horizontal-scroll').hScroll(60));
});

检查容器是否将空白属性设置为“nowrap”,如果没有则返回:

$.fn.hScroll = function (amount) {
    var $this = $(this);
    amount = amount || 120;
    $this.bind('DOMMouseScroll mousewheel', function (event) {
         var isHorizontal = $('.horizontal-scroll').css('white-space') == 'nowrap';
         if (!isHorizontal) return;
         var oEvent = event.originalEvent,
        direction = oEvent.detail ? oEvent.detail * -amount : oEvent.wheelDelta,
        position = $this.scrollLeft();
    position += direction > 0 ? -amount : amount;
    $this.scrollLeft(position);
    event.preventDefault();
});

};

我使用这个媒体查询来更新 white-space 属性:

@media (min-width: 768px) {
    .horizontal-scroll { white-space: nowrap !important; }
}

希望这可以帮助任何想要做同样的事情的人。

于 2019-01-09T05:07:26.770 回答
-1
why is mine failing?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style type="text/css">

        * {
          margin:0;
          padding:0;
        }
        
        
        
        #page-wrap {
          width:500%; /* 100% x length of panel */
          height:100%;
          overflow:hidden;
        }
        
        .panel {
          width:20%; /* 100% / length of panel */
          float:left;
          height:100%;
        }
        
        .panel .inner {padding:2em}
        
        
        /* Details (Ignore this!) */
        body {
          font:italic normal 13px/1.4 Georgia,Serif;
          color:#666;
        }
        
        h2 {
          font-weight:bold;
          font-size:200%;
          margin:0 0 1em;
        }
        
        p {margin:1.5em 0}
        
        #panel-1 {
          background-color:black;
          color:white;
        }
        
        #panel-2 {
          background-color:magenta;
          color:yellow;
        }
        
        #panel-3 {
          background-color:darkblue;
          color:lightgreen;
        }
        
        #panel-4 {
          background-color:pink;
          color:brown;
        }
        
        #panel-5 {
          background-color:darkred;
          color:cyan;
        }
        
        </style>
</head>
<body >
    <div  >
        <section style="height:500px;width:100%;color: rgb(29, 121, 202);">
            <h2>WWF History</h2>
            <p>The World Wide Fund for Nature (WWF) is an international organization working on issues regarding the conservation, research and restoration of the environment, formerly named the World Wildlife Fund. WWF was founded in 1961.</p>
          </section>
          
          <section style="height:500px;width:100%;color: rgb(223, 12, 135);">
            <h2>WWF's Symbol</h2>
            <p>The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of WWF.</p>
          </section>
          <section id="vane">
                <div id="page-wrap">
            <div class="panel" id="panel-1">
                <div class="inner"><h2>Eodem Modo Typi</h2><div style="-webkit-column-count:4;-moz-column-count:4;column-count:4;-webkit-column-gap:1em;-moz-column-gap:1em;column-gap:1em;text-align:right;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div><p style="font-size:500%;font-style:normal;text-align:right;">&rArr;</p></div>
            </div>
            <div class="panel" id="panel-2">
                <div class="inner"><h2>Facilisis At Vero Eros</h2><div style="-webkit-column-count:2;-moz-column-count:2;column-count:2;-webkit-column-gap:2em;-moz-column-gap:2em;column-gap:2em;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div></div>
            </div>
            <div class="panel" id="panel-3">
                <div class="inner"><img src="http://lorempixel.com/400/400/food/" alt="Image" width="400" height="400" style="float:right;margin:0 0 0 3em;"><h2>Euismod Tincidunt</h2><div><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p></div></div>
            </div>
            <div class="panel" id="panel-4">
                <div class="inner"><h2>Claritas est Etiam Processus Dynamicus</h2><img src="http://lorempixel.com/200/200/food/" alt="Image" width="200" height="200" style="float:right;margin:0 0 0 3em;"><div style="-webkit-column-count:2;-moz-column-count:2;column-count:2;-webkit-column-gap:2em;-moz-column-gap:2em;column-gap:2em;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div></div>
            </div>
            <div class="panel" id="panel-5">
                <div class="inner"><img src="http://lorempixel.com/400/400/food/" alt="Image" width="400" height="400" style="float:left;margin:0 3em 0 0;"><h2>Vulputate Velit Esse Molestie</h2><div style="-webkit-column-count:4;-moz-column-count:4;column-count:4;-webkit-column-gap:1em;-moz-column-gap:1em;column-gap:1em;"><p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p><p>Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit augue duis dolore te feugait nulla facilisi. Nam liber tempor cum soluta nobis eleifend option congue nihil imperdiet doming id quod mazim placerat facer possim assum.</p><p>Typi non habent claritatem insitam; est usus legentis in iis qui facit eorum claritatem. Investigationes demonstraverunt lectores legere me lius quod ii legunt saepius. Claritas est etiam processus dynamicus, qui sequitur mutationem consuetudium lectorum. Mirum est notare quam littera gothica, quam nunc putamus parum claram, anteposuerit litterarum formas humanitatis per seacula quarta decima et quinta decima. Eodem modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.</p></div></div>
            </div>
        </div>
          </section>
        
          <section  style="height:500px;width:200%; color: rgb(29, 121, 202);  ">
          <div  >
            <h2>WWF History</h2>
            <p >The World Wide Fund for Nature (WWF) is an international organization working on issues regarding the conservation, research and restoration of the environment, formerly named the World Wildlife Fund. WWF was founded in 1961.</p>
          </div>  
          </section>

          
          <section style="height:500px;width:100%;color: rgb(223, 12, 135);">
            <h2>WWF's Symbol</h2>
            <p>The Panda has become the symbol of WWF. The well-known panda logo of WWF originated from a panda named Chi Chi that was transferred from the Beijing Zoo to the London Zoo in the same year of the establishment of WWF.</p>
          </section>
    </div>
    
</body>
<script>
     (function() {
    function scrollHorizontally(e) {
        e = window.event || e;
        var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
        console.log(delta)
      var resultado =  document.getElementById('vane').scrollLeft -= (delta * 40 ); // Multiplied by 40
        e.preventDefault();
        console.log()
    }
    if (document.getElementById('vane').addEventListener) {
        // IE9, Chrome, Safari, Opera
        document.getElementById('vane').addEventListener('mousewheel', scrollHorizontally, false);
        // Firefox
        document.getElementById('vane').addEventListener('DOMMouseScroll', scrollHorizontally, false);
    } else {
        // IE 6/7/8
        document.getElementById('vane').attachEvent('onmousewheel', scrollHorizontally);
    }
})();
</script>
</html>

 
于 2022-02-11T16:11:14.717 回答