2012-12-24 33 views
10

我想水平滾動給定的元素。我找到的唯一方法是使用ScrollIntoView DOM方法,該方法允許將元素的底部與視圖底部或頂部對齊 - 與視圖頂部對齊。所以DOM scrollIntoView對齊頂部/底部,但左/右怎麼樣?

但是,如果元素相對於Y軸正常,我只想將其水平滾動?我怎樣才能將其左視圖與左視圖或右視圖與視圖右對齊?

編輯

這裏有更多的上下文。我有一個水平滾動條YUI表。我希望以編程方式將其滾動到某個TD節點。我不認爲window.scrollTo對我有幫助,因爲滾動條位於div元素上,而不是整個頁面上。

EDIT2

原來有一個重複與正確答案SO問題 - How can I scroll programmatically a div with its own scrollbars?

投票關閉礦井。

+0

jQuery'scrollTo'插件可以用各種方法處理這個問題。 jQuery是一個選項嗎? –

+0

我正在使用YUI。 jQuery如何做到這一點?它使用什麼DOM API? – mark

+0

看看'window.scrollTo'和'window.scrollBy' - 有點低調,但是你有完整的權力過程 –

回答

0

這是我以前用過的東西。可能有這樣做的更好,更有效的方式,但是這能夠完成的工作:你只需要確保該itema標籤與對應於目標id元素的href

$(".item").click(function(event){ 
    event.preventDefault(); 
    // I broke it down into variable to make it easier to read 
    var tgt_full = this.href, 
     parts = tgt_full.split("#"), 
     tgt_clean = parts[1], 
     tgt_offset = $("#"+tgt_clean).offset(), 
     tgt_left = tgt_offset.left; 

    $('html, body').animate({scrollLeft:tgt_left}, 1000, "easeInOutExpo");   
}) 

HTML:

<a href="#one">go to section 1</a> 
... 
<section id="one"> Section 1</section> 

希望這有助於!

+0

它如何幫助我將表格水平滾動到某個TD節點?滾動條位於包含表格的div元素上。 – mark

+0

對不起,我誤解了這個問題...... – Maroshii

0

我最近有一個表頭有一個問題,輸入爲每列的過濾器。通過過濾器標籤會移動焦點,但是如果其中一個輸入不可見或部分可見,它只會將輸入視爲可見,並且我被要求將全部輸入和列顯示出來。然後我被要求做同樣的事情,如果倒退到左邊。

此鏈接幫助讓我開始:http://www.webdeveloper.com/forum/showthread.php?197612-scrollIntoView-horizontal

簡短的回答是,你要使用:

document.getElementById('myElement').scrollLeft = 50; 

或:

$('#myElement')[0].scrollLeft = 50; 

這裏是我的解決方案(這可能是這個問題過分矯枉過正,但也許它會幫助某人):

// I used $.on() because the table was re-created every time the data was refreshed 
// #tableWrapper is the div that limits the size of the viewable table 
// don't ask me why I had to move the head head AND the body, they were in 2 different tables & divs, I didn't make the page 

$('#someParentDiv').on('focus', '#tableWrapper input', function() { 
    var tableWidth = $('#tableWrapper')[0].offsetWidth; 
    var cellOffset = $(this).parent()[0].offsetLeft; 
    var cellWidth = $(this).parent()[0].offsetWidth; 
    var cellTotalOffset = cellOffset + cellWidth; 

     // if cell is cut off on the right 
    if (cellTotalOffset > tableWidth) { 
     var difference = cellTotalOffset - tableWidth; 
     $('#tableWrapper').find('.dataTables_scrollHead')[0].scrollLeft = difference; 
     $('#tableWrapper').find('.dataTables_scrollBody')[0].scrollLeft = difference; 
    } 
     // if cell is cut off on the left 
    else if ($('#tableWrapper').find('.dataTables_scrollHead')[0].scrollLeft > cellOffset) { 
     $('#tableWrapper').find('.dataTables_scrollHead')[0].scrollLeft = cellOffset; 
     $('#tableWrapper').find('.dataTables_scrollBody')[0].scrollLeft = cellOffset; 
    } 
}); 
相關問題