简体   繁体   English

使用jQuery scollLeft()方法默认情况下向右滚动,我的代码有什么问题?

[英]using jQuery scollLeft() method to scroll to the right by default, what is wrong with my code?

Here is my code: 这是我的代码:

<head>
    <title>Labs</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var left = $('.entry-content').width();
$('.entry-content').scrollLeft(left);
</script>
</head>
<body>
    <div class="container"> 
        <div class="entry-content"><img src="map.png"></div>
    </div>
</body>

I want the scroll to display to the far right automatically when the user visits the page. 我希望滚动条在用户访问页面时自动显示在最右边。 Currently it scrolls to the left by default. 当前,默认情况下它滚动到左侧。 Please tell me what's wrong with my code. 请告诉我我的代码有什么问题。

generally with positional situations like this you'd just say var left = $('.entry-content').width() * -1; 通常在这样的位置情况下,您只会说var left = $('.entry-content').width() * -1; , does that not work in this case? ,在这种情况下不行吗?

You should execute your code when the page has finished loading (and so the image width is known) and for that you need to insert your code in the handler for the window.load event, like this: 您应该在页面加载完成后执行代码(因此图像宽度是已知的),为此,您需要将代码插入window.load事件的处理程序中,如下所示:

<head>
    <title>Labs</title>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<script>
$(window).on('load', function() {
    var left = $('.entry-content').width();
    $('.entry-content').scrollLeft(left);
});
</script>
<body>
    <div class="container"> 
        <div class="entry-content"><img src="map.png"></div>
    </div>
</body>

Make sure you include that script after the DOM element, or wrap it in a DOMContentLoaded handler . 确保在DOM元素之后包含该脚本,或将其包装在DOMContentLoaded处理程序中 For example: 例如:

<script>
    document.addEventListener('DOMContentLoaded', function() {
        var left = $('.entry-content').width();
        $('.entry-content').scrollLeft(left);
    });
</script>

In your example it's impossible for the selectors $('.entry-content') to select the actual element, because it does not yet exist when the javascript code runs. 在您的示例中,选择器$('.entry-content')无法选择实际元素,因为在运行JavaScript代码时该元素尚不存在。 The DOM is parsed top to bottom, and any scripts that are found along the way are executed immediately. DOM是从上到下解析的,在此过程中找到的所有脚本都将立即执行。


As Nelson also points out in his answer, it is also a good idea to keep in mind that the image might take a while to load. 正如尼尔森在回答中所指出的那样,记住图像可能需要一段时间才能加载,这也是一个好主意。 Only once it is loaded, the image will start to occupy the actual space it needs. 仅在加载图像后,图像才会开始占用其所需的实际空间。 So, if you measure the dimensions of .entry-content before the image loads, you get a number that is inaccurate if the image requires more horizontal space than the containing element naturally occupies. 因此,如果在加载图像之前测量.entry-content的尺寸,则在图像需要的水平空间比包含元素自然占据的水平空间更多的情况下,您会得到不准确的数字。

To fix this you can listen for the "load" event on window instead, which will always fire after DOMContentLoaded, and not before all resources (among which your image) have been loaded: 要解决此问题,您可以改为监听window上的"load"事件 ,该事件将始终 DOMContentLoaded之后而不是在所有资源(其中包括您的图像)已加载之前触发:

<script>
    window.addEventListener('load', function() {
        var left = $('.entry-content').width();
        $('.entry-content').scrollLeft(left);
    });
</script>

This example is equivalent to Nelson's answer . 这个例子等同于尼尔森的答案

Try following script: 尝试以下脚本:

<script>
$(document).ready(function(){
    var left = document.querySelector('div.entry-content').getBoundingClientRect().left;
    window.scrollBy(left,0);
});
</script>

I used the getBoundingClientRect() to get the position of div element with .entry-content class attribute. 我使用getBoundingClientRect()获取具有.entry-content class属性的div元素的位置。 The left property gives x-offset value from the left of the browser window. left属性从浏览器窗口的左侧给出x-offset值。 Now, i use that value to scroll the window using window.scrollBy(x,y) method. 现在,我使用该值使用window.scrollBy(x,y)方法滚动窗口。

For your snippet to work , you need to make some changes in your html : 为了使您的代码段正常工作 ,您需要在html中进行一些更改:

 <script>
    $(document).ready(function(){
      var left = $('.entry-content').width();
      $('.entry-content').scrollLeft(left);
    });
 </script>

   <div class="container"> 
        <div class="entry-content" style="width:30%;overflow:auto"><img src="map.png"></div>
    </div>

Notice that i have restricted the size to 30% for div and setting overflow to true will cause div to show scrollbars if image width is more then width of the div. 请注意,我已将div的尺寸限制为30%,并且将overflow设置为true会导致div在图像宽度大于div宽度时显示滚动条。 Now left will contain the width of the div element with .entry-content class applied and since the content of div can be scrolled now with scrollbars available, you can call scrollLeft(value) method on the div to scroll contents of this div to the left. 现在左侧将包含应用了.entry-content类的div元素的宽度,并且由于现在可以使用可用的滚动条滚动div的内容,因此您可以在div上调用scrollLeft(value)方法将该div的内容滚动到剩下。 If you want to scroll to the extreme right of the image , you should pass amountToScroll = widthOfImage-widthOfDivContaing image to the scrollLeft(amountToScroll) ie 如果要滚动到图像的最右端 ,则应将amountToScroll = widthOfImage-widthOfDivContaing图像传递给scrollLeft(amountToScroll),即

<script>
    $(document).ready(function(){
     var amountToScroll = $('img').width() - $('.entry-content').width()
    $('.entry-content').scrollLeft(amountToScroll);
    });
 </script>

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM