2015-03-10 2 views
2

У меня проблемы с прокруткой элемента внутри прокручиваемого div.Прокрутка до элемента внутри прокручиваемого div

Мой код довольно прост, и он имитирует точную проблему, которую я испытываю в своем более крупном проекте. Когда я нажимаю на текст с левой стороны, он должен прокручиваться до элемента с тем же id с правой стороны, но не работает. Он всегда прокручивается в другую позицию, и я не знаю, почему.

Если вам удастся помочь мне, вы также можете дать краткое объяснение, что я делаю неправильно. Я новичок в jQuery. Благодаря

JSFiddle

$('.left span').click(function() { 
    var id = $(this).attr('id'); 
    var element = $('.right span[id="' + id + '"]'); 
    $('.right').animate({ scrollTop: element.offset().top }, 500); 
}); 
+0

Не указывайте тот же идентификатор элемента сначала исправить это. –

+0

Это должен быть пример, который имитирует мою проблему. В моем проекте у меня есть более умный способ настроить таргетинг на эти элементы. Исправление одинаковых идентификаторов ничего не меняет. – Hnus

ответ

6

Хорошо ... Итак, у вас было несколько проблем с вашим исходным кодом.

Во-первых, не дублируйте идентификаторы, это плохая практика, и это неверно.

Следующая проблема, с которой вы столкнулись, заключается в том, что вы получали офсетную верхнюю часть ваших интервалов. Offset будет:

Получить текущие координаты первого элемента, или установить координаты каждого элемента в наборе соответствующих элементов, относительно к документу.

Акцент на «относительно документа».

Вам нужна позиция. Position будет:

Получить текущие координаты первого элемента в наборе соответствующих элементов , по отношению к смещению родителя.

Акцент на «относительно родителя смещения».

Теперь основная проблема заключалась в том, что вы получали смещение после щелчка. Какой вид работал на ваш первый клик, но после этого все значения смещения сверху были искажены новой позицией прокрутки.

Чтобы исправить это, вам нужно пройти через элементы и получить их положение, прежде чем вы начнете щелкнуть.

Попробуйте что-то вроде этого:

$('.js_scrollTo').each(function() { // for each span 
 
    var target = $(this).text(); // get the text of the span 
 
    var scrollPos = $('#' + target).position().top; // use the text of the span to create an ID and get the top position of that element 
 
    $(this).click(function() { // when you click each span 
 
     $('.right').animate({ // animate your right div 
 
      scrollTop: scrollPos // to the position of the target 
 
     }, 400); 
 
    }); 
 
});
.left { 
 
    position: fixed; 
 
    top: 0; 
 
    left: 0; 
 
} 
 
.right { 
 
    position: relative; /* you'll need some position here for jQuery's position to work, otherwise it will be based on the document */ 
 
    width: 50%; 
 
    height: 200px; 
 
    overflow: scroll; 
 
    float: right; 
 
    display: block; 
 
} 
 
.right span { 
 
    background-color: red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> 
 
<div class="left"> 
 
    <div class="js_scrollTo">test1</div> 
 
    <div class="js_scrollTo">test2</div> 
 
    <div class="js_scrollTo">test3</div> 
 
</div> 
 
<div class="right">Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit ameContrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit ame<span id="test1">test1</span>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit ameContrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit ame<span id="test2">test2</span> 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit ameContrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit ame<span id="test3">test3</span>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit ameContrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsumRenaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit ameContrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit ame<span id="test3">assasdasdasd</span>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit ameContrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem</div>

+0

Я не мог надеяться на лучший ответ! Я многому научился. Спасибо, что на самом деле прочитали то, о чем я просил, и пытались понять мою проблему, прежде чем отвечать. спасибо – Hnus

1

вы не должны давать один и тот же идентификатор дважды на одной странице. дать каждому пролету в праве, например:

<span id="1to"></span> 

и вызовите функцию анимации для элемента с # + ид + в

var element = $('#'+id+'to'); 
$('.right').animate({ scrollTop: element.offset().top }, 500); 

также можно расположить «меню» .left в фиксированном положении и анимировать весь html, тело до определенного положения.

попробовать эту скрипку: https://jsfiddle.net/xchqw7uz/

работает, как вы собираетесь его. и проще в использовании, так как вам не нужно столько идентификаторов

+0

Я сделал, и он работает так же, как и раньше. http://jsfiddle.net/ber63qnz/8/ – Hnus

+0

https://jsfiddle.net/xchqw7uz/ новая скрипка –

+0

Пожалуйста, не изменяйте правила. Я мог бы заставить его работать, когда я пытаюсь анимировать весь html. Мне нужно, чтобы он работал внутри div. – Hnus

0

У меня были проблема прокрутки элемента внутри прокрутки DIV (или другой прокруткой элемента) ведьма может быть внутри другой прокруткой элемента ведьмы может быть внутри прокрутка страницы или другим прокручиваемым элементом и так далее.

я провел некоторое время и сделал следующее решение:

utils.scrollVerticallyToElement(jqElement, true); 

где jqElement является элемент (обернутый в объект JQuery) для перехода к, второй аргумент является флагом, который указывает, является ли для анимации прокрутки процесс (истинно для анимации) и scrollVerticallyToElement представляет собой метод следующего объекта:

var utils = { 
    clearAllSelections: function() { 
     //clearing selected text if any 
     if (document.selection && document.selection.empty) { 
      document.selection.empty(); 
     } else if (window.getSelection) { 
      var sel = window.getSelection(); 
      sel.removeAllRanges(); 
     } 
    }, 

    getWindowClientVisibleRect: function() { 
     var html = document.documentElement; 
     var body = document.body; 
     var doc = (html && html.clientWidth) ? html : body; 

     var scrollTop = window.pageYOffset || html.scrollTop || body.scrollTop; 
     var scrollLeft = window.pageXOffset || html.scrollLeft || body.scrollLeft; 

     var clientTop = html.clientTop || body.clientTop || 0; 
     var clientLeft = html.clientLeft || body.clientLeft || 0; 

     var windowLeft = scrollLeft - clientLeft; 
     var windowRight = doc.clientWidth + windowLeft; 
     var windowTop = scrollTop - clientTop; 
     var windowBottom = doc.clientHeight + windowTop; 

     return { left: windowLeft, top: windowTop, right: windowRight, bottom: windowBottom }; 
    }, 

    getScrollableElementVisibleRect: function (element) { 
     var left = element.scrollLeft - element.clientLeft; 
     var top = element.scrollTop - element.clientTop; 

     return { left: left, top: top, right: element.clientWidth + left, bottom: element.clientHeight + top }; 
    }, 

    getCoordinates: function (element) { 
     var top = 0, left = 0; 

     if (element.getBoundingClientRect) { 
      var windowRect = this.getWindowClientVisibleRect(); 
      var elementRect = element.getBoundingClientRect(); 

      top = Math.round(elementRect.top + windowRect.top); 
      left = Math.round(elementRect.left + windowRect.left); 
     } 
     else { 
      while (element) { 
       top = top + parseInt(element.offsetTop); 
       left = left + parseInt(element.offsetLeft); 
       element = element.offsetParent; 
      } 
     } 
     return { top: top, left: left, right: left + element.offsetHeight, bottom: top + element.offsetHeight }; 
    }, 

    scrollWindowVerticallyToElement: function (element) { 
     var elemCoord = this.getCoordinates(element); 
     var wndRect = this.getWindowClientVisibleRect(); 

     if (elemCoord.top < wndRect.top) { 
      window.scrollTo(wndRect.left, elemCoord.top); 
     } 
     else if (elemCoord.bottom > wndRect.bottom) { 
      window.scrollBy(0, elemCoord.bottom - wndRect.bottom); 
     } 
    }, 

    scrollVerticallyToElement: function (jqElement, useAnimation) { 
     if (!jqElement || !jqElement.parent) { 
      return; 
     } 

     var scrollToElement; 
     if (!useAnimation) { 
      scrollToElement = function(jq, scrollValue) { 
       jq.scrollTop(scrollValue); 
      }; 
     } 
     else { 
      scrollToElement = function (jq, scrollValue) { 
       jq.animate({ 
        scrollTop: scrollValue 
       }, 'fast'); 
      }; 
     } 

     jqElement.parents().each(function() { 
      var jqThis = $(this); 

      var top = Math.round(jqElement.position().top); 
      var bottom = top + jqElement.innerHeight(); 

      var parentTop = Math.round(jqThis.position().top); 
      var parentBottom = parentTop + jqThis.innerHeight(); 

      if (top < parentTop && jqThis.scrollTop() > 0) { 
       scrollToElement(jqThis, jqThis.scrollTop() - parentTop + top); 
      } else if (bottom > parentBottom) { 
       scrollToElement(jqThis, jqThis.scrollTop() - parentBottom + bottom); 
      } 
     }); 

     this.scrollWindowVerticallyToElement(jqElement.get(0)); 
    } 
}; 

Этот код был протестирован в Opera, Firefox и IE. И это действительно работает!

Пожалуйста, заполните, пожалуйста, utils объект в вашем проекте, если вам нужно (вы можете даже переименовать его, если вам нужно).

Смежные вопросы