2009-03-11 50 views
76

Tôi có một cuộn div và tôi muốn có một liên kết khi tôi nhấp vào nó, nó sẽ buộc div này cuộn để xem phần tử bên trong. tôi đã viết JavasSript của nó như thế này:Cách cuộn đến một phần tử bên trong div?

document.getElementById(chr).scrollIntoView(true); 

nhưng điều này cuộn tất cả các trang trong khi di chuyển các div riêng của mình. Cách sửa lỗi đó?

Tôi muốn nói nó như thế

MyContainerDiv.getElementById(chr).scrollIntoView(true); 
+0

Scrolltop không phải lúc nào trả lại giá trị có thể sử dụng. Tôi có xu hướng sử dụng một 'SetTimeout' trong hàm' $ (document) .ready ({}) 'và đặt' focus() 'thành phần tử bạn muốn cuộn đến. Làm việc cho tôi – DerpyNerd

Trả lời

211

Bạn cần phải nhận đầu bù đắp của phần tử mà bạn muốn di chuyển vào xem, so với cha mẹ của nó (vùng chứa div cuộn):

var myElement = document.getElementById('element_within_div'); 
var topPos = myElement.offsetTop; 

Biến topPos giờ được đặt ở khoảng cách giữa phần đầu của div cuộn và phần tử bạn muốn hiển thị (tính bằng pixel).

Bây giờ chúng ta nói div để di chuyển đến vị trí đó sử dụng scrollTop:

document.getElementById('scrolling_div').scrollTop = topPos; 

Nếu bạn đang sử dụng khuôn khổ JS nguyên mẫu, bạn muốn làm điều tương tự như thế này:

var posArray = $('element_within_div').positionedOffset(); 
$('scrolling_div').scrollTop = posArray[1]; 

Một lần nữa, điều này sẽ di chuyển div để các phần tử bạn muốn xem là chính xác ở phía trên (hoặc nếu không thể, cuộn như xa xuống vì nó có thể để nó có thể nhìn thấy).

+6

Điều này thực sự hữu ích! Nếu bạn muốn đặt cuộn nhiều lần bạn cần phải bù đắp bởi vị trí cuộn hiện tại của bạn. Đây là cách tôi đã làm nó trong jQuery: $ ('# scrolling_div'). ScrollTop ($ ('# scrolling_div'). ScrollTop() + $ ('# element_within_div'). Position(). Top); – DenimChicken

+0

không hoạt động nữa, offsetTop luôn bằng 0 – singe3

+2

Cảnh giác rằng yêu cầu 'myElement.offsetTop' sẽ kích hoạt reflow (sắp xếp bố cục) có thể là [nút cổ chai hiệu suất] (https://developers.google.com/web/ Nguyên tắc cơ bản/hiệu suất/hiển thị/tránh-lớn-phức tạp-bố trí-và-bố trí-thrashing? hl = vi # tránh-bố trí-thrashing) – Kestutis

56

Bạn sẽ phải tìm ra vị trí của các phần tử trong DIV bạn muốn di chuyển đến, và thiết lập thuộc tính scrollTop.

divElem.scrollTop = 0; 

Cập nhật:

Mẫu mã để di chuyển lên hoặc xuống

function move_up() { 
    document.getElementById('divElem').scrollTop += 10; 
    } 

    function move_down() { 
    document.getElementById('divElem').scrollTop -= 10; 
    } 
+2

tôi muốn cuộn chế độ xem, để xem nó không cuộn với một giá trị nhất định –

7

Mã nên là:

var divElem = document.getElementById('scrolling_div'); 
var chElem = document.getElementById('element_within_div'); 
var topPos = divElem.offsetTop; 
divElem.scrollTop = topPos - chElem.offsetTop; 

Bạn muốn di chuyển phần chênh lệch giữa vị trí hàng đầu trẻ em và vị trí hàng đầu của div.

Nhận quyền truy cập vào yếu tố con sử dụng:

var divElem = document.getElementById('scrolling_div'); 
var numChildren = divElem.childNodes.length; 

và vân vân ....

+1

Không phải dòng thứ hai thực sự đọc 'var chElem = document.getElementById ('element_within_div');' và dòng thứ 3 đọc 'var topPos = divElem.offsetTop;'? – jayp

0

tài Animated cuộn

Dưới đây là một ví dụ về làm thế nào để lập trình di chuyển một <div> theo chiều ngang, mà không cầnJQuery. Để cuộn theo chiều dọc, thay vào đó, bạn sẽ thay thế các ghi của JavaScript thành scrollLeft bằng scrollTop.

JSFiddle

https://jsfiddle.net/fNPvf/38536/

HTML

<!-- Left Button. --> 
<div style="float:left;"> 
    <!-- (1) Whilst it's pressed, increment the scroll. When we release, clear the timer to stop recursive scroll calls. --> 
    <input type="button" value="«" style="height: 100px;" onmousedown="scroll('scroller',3, 10);" onmouseup="clearTimeout(TIMER_SCROLL);"/> 
</div> 
<!-- Contents to scroll. --> 
<div id="scroller" style="float: left; width: 100px; height: 100px; overflow: hidden;"> 
    <!-- <3 --> 
    <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" alt="image large" style="height: 100px" /> 
</div> 
<!-- Right Button. --> 
<div style="float:left;"> 
    <!-- As (1). (Use a negative value of 'd' to decrease the scroll.) --> 
    <input type="button" value="»" style="height: 100px;" onmousedown="scroll('scroller',-3, 10);" onmouseup="clearTimeout(TIMER_SCROLL);"/> 
</div> 

Javascript

// Declare the Shared Timer. 
var TIMER_SCROLL; 
/** 
Scroll function. 
@param id Unique id of element to scroll. 
@param d Amount of pixels to scroll per sleep. 
@param del Size of the sleep (ms).*/ 
function scroll(id, d, del){ 
    // Scroll the element. 
    document.getElementById(id).scrollLeft += d; 
    // Perform a delay before recursing this function again. 
    TIMER_SCROLL = setTimeout("scroll('"+id+"',"+d+", "+del+");", del); 
} 

Tín dụng cho Dux.


Auto Animated cuộn

Bên cạnh đó, đây là chức năng cho di chuyển một <div> hoàn toàn sang trái và phải. Điều duy nhất chúng tôi thay đổi ở đây là chúng tôi kiểm tra xem phần mở rộng đầy đủ của cuộn đã được sử dụng chưa trước khi thực hiện một cuộc gọi đệ quy để cuộn lại.

JSFiddle

https://jsfiddle.net/0nLc2fhh/1/

HTML

<!-- Left Button. --> 
<div style="float:left;"> 
    <!-- (1) Whilst it's pressed, increment the scroll. When we release, clear the timer to stop recursive scroll calls. --> 
    <input type="button" value="«" style="height: 100px;" onclick="scrollFullyLeft('scroller',3, 10);"/> 
</div> 
<!-- Contents to scroll. --> 
<div id="scroller" style="float: left; width: 100px; height: 100px; overflow: hidden;"> 
    <!-- <3 --> 
    <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" alt="image large" style="height: 100px" /> 
</div> 
<!-- Right Button. --> 
<div style="float:left;"> 
    <!-- As (1). (Use a negative value of 'd' to decrease the scroll.) --> 
    <input type="button" value="»" style="height: 100px;" onclick="scrollFullyRight('scroller',3, 10);"/> 
</div> 

Javascript

// Declare the Shared Timer. 
var TIMER_SCROLL; 
/** 
Scroll fully left function; completely scrolls a <div> to the left, as far as it will go. 
@param id Unique id of element to scroll. 
@param d Amount of pixels to scroll per sleep. 
@param del Size of the sleep (ms).*/ 
function scrollFullyLeft(id, d, del){ 
    // Fetch the element. 
    var el = document.getElementById(id); 
    // Scroll the element. 
    el.scrollLeft += d; 
    // Have we not finished scrolling yet? 
    if(el.scrollLeft < (el.scrollWidth - el.clientWidth)) { 
     TIMER_SCROLL = setTimeout("scrollFullyLeft('"+id+"',"+d+", "+del+");", del); 
    } 
} 

/** 
Scroll fully right function; completely scrolls a <div> to the right, as far as it will go. 
@param id Unique id of element to scroll. 
@param d Amount of pixels to scroll per sleep. 
@param del Size of the sleep (ms).*/ 
function scrollFullyRight(id, d, del){ 
    // Fetch the element. 
    var el = document.getElementById(id); 
    // Scroll the element. 
    el.scrollLeft -= d; 
    // Have we not finished scrolling yet? 
    if(el.scrollLeft > 0) { 
     TIMER_SCROLL = setTimeout("scrollFullyRight('"+id+"',"+d+", "+del+");", del); 
    } 
} 
2

Nếu bạn đang sử dụng jQuery, bạn có thể di chuyển với một hình ảnh động bằng cách sử dụng sau đây:

$(MyContainerDiv).animate({scrollTop: $(MyContainerDiv).scrollTop() + ($('element_within_div').offset().top - $(MyContainerDiv).offset().top)}); 

Các hình ảnh động là tùy chọn: bạn cũng có thể lấy giá trị scrollTop tính ở trên và đặt nó trực tiếp vào bất động sản scrollTop của container.

2

Để di chuyển một phần tử vào quan điểm của một div, chỉ khi cần thiết, bạn có thể sử dụng scrollIfNeeded chức năng này:

function scrollIfNeeded(element, container) { 
 
    if (element.offsetTop < container.scrollTop) { 
 
    container.scrollTop = element.offsetTop; 
 
    } else { 
 
    const offsetBottom = element.offsetTop + element.offsetHeight; 
 
    const scrollBottom = container.scrollTop + container.offsetHeight; 
 
    if (offsetBottom > scrollBottom) { 
 
     container.scrollTop = offsetBottom - container.offsetHeight; 
 
    } 
 
    } 
 
} 
 

 
document.getElementById('btn').addEventListener('click', ev => { 
 
    ev.preventDefault(); 
 
    scrollIfNeeded(document.getElementById('goose'), document.getElementById('container')); 
 
});
.scrollContainer { 
 
    overflow-y: auto; 
 
    max-height: 100px; 
 
    position: relative; 
 
    border: 1px solid red; 
 
    width: 120px; 
 
} 
 

 
body { 
 
    padding: 10px; 
 
} 
 

 
.box { 
 
    margin: 5px; 
 
    background-color: yellow; 
 
    height: 25px; 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
} 
 

 
#goose { 
 
    background-color: lime; 
 
}
<div id="container" class="scrollContainer"> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div id="goose" class="box">goose</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
    <div class="box">duck</div> 
 
</div> 
 

 
<button id="btn">scroll to goose</button>

0

Dưới đây là một giải pháp JavaScript tinh khiết đơn giản mà làm việc cho một số mục tiêu (giá trị cho scrollTop), phần tử DOM mục tiêu hoặc một số trường hợp Chuỗi đặc biệt:

/** 
* target - target to scroll to (DOM element, scrollTop Number, 'top', or 'bottom' 
* containerEl - DOM element for the container with scrollbars 
*/ 
var scrollToTarget = function(target, containerEl) { 
    // Moved up here for readability: 
    var isElement = target && target.nodeType === 1, 
     isNumber = Object.prototype.toString.call(target) === '[object Number]'; 

    if (isElement) { 
     containerEl.scrollTop = target.offsetTop; 
    } else if (isNumber) { 
     containerEl.scrollTop = target; 
    } else if (target === 'bottom') { 
     containerEl.scrollTop = containerEl.scrollHeight - containerEl.offsetHeight; 
    } else if (target === 'top') { 
     containerEl.scrollTop = 0; 
    } 
}; 

Và đây là một số ví dụ về việc sử dụng:

// Scroll to the top 
var scrollableDiv = document.getElementById('scrollable_div'); 
scrollToTarget('top', scrollableDiv); 

hoặc

// Scroll to 200px from the top 
var scrollableDiv = document.getElementById('scrollable_div'); 
scrollToTarget(200, scrollableDiv); 

hoặc

// Scroll to targetElement 
var scrollableDiv = document.getElementById('scrollable_div'); 
var targetElement= document.getElementById('target_element'); 
scrollToTarget(targetElement, scrollableDiv); 
0

Đây là những gì cuối cùng đã phục vụ tôi

/** Set parent scroll to show element 
* @param element {object} The HTML object to show 
* @param parent {object} The HTML object where the element is shown */ 
var scrollToView = function(element, parent) { 
    //Algorithm: Accumulate the height of the previous elements and add half the height of the parent 
    var offsetAccumulator = 0; 
    parent = $(parent); 
    parent.children().each(function() { 
     if(this == element) { 
      return false; //brake each loop 
     } 
     offsetAccumulator += $(this).innerHeight(); 
    }); 
    parent.scrollTop(offsetAccumulator - parent.innerHeight()/2); 
} 
Các vấn đề liên quan