我試圖在頁面上設置滾動位置,以便滾動條一直滾動到頂部。設置滾動位置
我想我需要這樣的事情,但它不工作:
(function() { alert('hello'); document.body.scrollTop = 0; }());
任何想法?
我試圖在頁面上設置滾動位置,以便滾動條一直滾動到頂部。設置滾動位置
我想我需要這樣的事情,但它不工作:
(function() { alert('hello'); document.body.scrollTop = 0; }());
任何想法?
您可以使用window.scrollTo()
,像這樣:
window.scrollTo(0, 0); // values are x,y-offset
注意,如果你要滾動的元素,而不是完整的窗口,元素沒有scrollTo
和scrollBy
方法。你應該:
var el = document.getElementById("myel"); // Or whatever method to get the element
// To set the scroll
el.scrollTop = 0;
el.scrollLeft = 0;
// To increment the scroll
el.scrollTop += 100;
el.scrollLeft += 100;
你也可以模仿window.scrollTo
和window.scrollBy
功能,所有在網頁中existant HTML元素:
Object.defineProperty(HTMLElement.prototype, "scrollTo", {
value: function(x, y) {
el.scrollTop = y;
el.scrollLeft = x;
},
enumerable: false
});
Object.defineProperty(HTMLElement.prototype, "scrollBy", {
value: function(x, y) {
el.scrollTop += y;
el.scrollLeft += x;
},
enumerable: false
});
所以你可以做:
var el = document.getElementById("myel"); // Or whatever method to get the element, again
// To set the scroll
el.scrollTo(0, 0);
// To increment the scroll
el.scrollBy(100, 100);
注意:鼓勵Object.defineProperty
,因爲直接將屬性添加到prototype
是一個壞習慣(當你看到它時:-)。
非常感謝你 – yussan 2018-01-11 02:57:32