Javascript 如何滚动到div中的元素?
我有一个滚动的Javascript 如何滚动到div中的元素?,javascript,html,scroll,Javascript,Html,Scroll,我有一个滚动的div,我想在单击它时有一个事件,它将强制该div滚动以查看其中的元素。 我这样编写了它的JavasSript: document.getElementById(chr).scrollIntoView(true); var posArray = $('element_within_div').positionedOffset(); $('scrolling_div').scrollTop = posArray[1]; 但这会在滚动div本身的同时滚动整个页面。 如何解决这个问题
div
,我想在单击它时有一个事件,它将强制该div
滚动以查看其中的元素。
我这样编写了它的JavasSript:
document.getElementById(chr).scrollIntoView(true);
var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];
但这会在滚动div
本身的同时滚动整个页面。
如何解决这个问题
我想这样说:
MyContainerDiv.getElementById(chr.scrollIntoView)(true)代码>您必须找到要滚动到的DIV中元素的位置,并设置scrollTop属性
divElem.scrollTop = 0;
更新:
上移或下移的示例代码
function move_up() {
document.getElementById('divElem').scrollTop += 10;
}
function move_down() {
document.getElementById('divElem').scrollTop -= 10;
}
您需要获取要滚动到视图中的元素相对于其父元素(滚动div容器)的顶部偏移量:
变量topPos现在设置为滚动div顶部与希望可见的元素之间的距离(以像素为单位)
现在,我们告诉div使用scrollTop
滚动到该位置:
document.getElementById('scrolling_div').scrollTop = topPos;
如果您使用的是prototype JS框架,您也可以这样做:
document.getElementById(chr).scrollIntoView(true);
var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];
同样,这将滚动div,使您希望看到的元素正好位于顶部(如果不可能,则尽可能向下滚动以使其可见)。代码应为:
var divElem = document.getElementById('scrolling_div');
var chElem = document.getElementById('element_within_div');
var topPos = divElem.offsetTop;
divElem.scrollTop = topPos - chElem.offsetTop;
您希望滚动子顶部位置和div顶部位置之间的差异
使用以下命令访问子元素:
var divElem = document.getElementById('scrolling_div');
var numChildren = divElem.childNodes.length;
等等……用户动画滚动
下面是一个示例,说明如何通过编程水平滚动
,而不使用JQuery。要垂直滚动,可以将JavaScript对scrollLeft
的写入替换为scrollTop
JSFiddle
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>
<!-- 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>
归功于
自动动画滚动
此外,以下是将
完全向左和向右滚动的功能。我们在这里所做的唯一更改是,在再次递归调用scroll之前,检查是否使用了scroll的完整扩展
JSFiddle
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>
<!-- 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 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);
}
// 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);
}
}
//声明共享计时器。
变量计时器滚动;
/**
完全向左滚动功能;将a完全向左滚动,直到滚动不动为止。
@参数id要滚动的元素的唯一id。
@参数d每次睡眠要滚动的像素量。
@睡眠的参数del大小(ms)*/
函数scrollFullyLeft(id、d、del){
//获取元素。
var el=document.getElementById(id);
//滚动元素。
el.left+=d;
//我们还没有完成滚动吗?
如果(el.scrollLeft<(el.scrollWidth-el.clientWidth)){
TIMER_SCROLL=setTimeout(“scrollFullyLeft(“+id+”,“+d+”,“+del+”;”,del);
}
}
/**
完全向右滚动功能;将a完全向右滚动,直到滚动不动为止。
@参数id要滚动的元素的唯一id。
@参数d每次睡眠要滚动的像素量。
@睡眠的参数del大小(ms)*/
函数scrollFullyRight(id、d、del){
//获取元素。
var el=document.getElementById(id);
//滚动元素。
el.left-=d;
//我们还没有完成滚动吗?
如果(左上角>0){
TIMER_SCROLL=setTimeout(“scrollFullyRight(“+id+”,“+d+”,“+del+”;”,del);
}
}
如果使用jQuery,则可以使用以下命令滚动动画:
$(MyContainerDiv).animate({scrollTop: $(MyContainerDiv).scrollTop() + ($('element_within_div').offset().top - $(MyContainerDiv).offset().top)});
动画是可选的:您还可以获取上面计算的scrollTop值,并将其直接放入容器的属性中。要将元素滚动到div视图中,仅在需要时,您可以使用此功能:
divElem.scrollTop = 0;
需要的函数(元素、容器){
if(element.offsetTop滚动底部){
container.scrollTop=offsetBottom-container.offsetHeight;
}
}
}
document.getElementById('btn')。addEventListener('click',ev=>{
ev.preventDefault();
scrollIfNeeded(document.getElementById('goose')、document.getElementById('container');
});代码>
.scrollContainer{
溢出y:自动;
最大高度:100px;
位置:相对位置;
边框:1px纯红;
宽度:120px;
}
身体{
填充:10px;
}
.盒子{
保证金:5px;
背景颜色:黄色;
高度:25px;
显示器:flex;
对齐项目:居中;
证明内容:中心;
}
#鹅{
背景色:石灰;
}
鸭子
鸭子
鸭子
鸭子
鸭子
鸭子
鸭子
鸭子
鹅
鸭子
鸭子
鸭子
鸭子
滚动到goose
这里有一个简单的纯JavaScript解决方案,它适用于目标数字(scrollTop的值)、目标DOM元素或一些特殊的字符串大小写:
/**
* 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;
}
};
下面是一些用法示例:
// Scroll to the top
var scrollableDiv = document.getElementById('scrollable_div');
scrollToTarget('top', scrollableDiv);
或
或
这就是我最终得到的
/** 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);
}
使用jQuery和动画的另一个示例
var container = $('#container');
var element = $('#element');
container.animate({
scrollTop: container.scrollTop = container.scrollTop() + element.offset().top - container.offset().top
}, {
duration: 1000,
specialEasing: {
width: 'linear',
height: 'easeOutBounce'
},
complete: function (e) {
console.log("animation completed");
}
});
方法1-平滑滚动到元素内部的元素
var-box=document.querySelector('.box'),
targetElm=document.querySelector('.boxChild');// 有两个事实:
1) safari不支持组件scrollIntoView
2) JS framework jQuery可以完成如下工作:
document.getElementById(chr).scrollIntoView(true);
var posArray = $('element_within_div').positionedOffset();
$('scrolling_div').scrollTop = posArray[1];
parent='某些父div的css位置===“fixed”| |“html,body”;
$(父).animate({scrollTop:$(子).offset().top},持续时间)
浏览器会自动滚动到获得焦点的元素,因此您也可以这样做,将需要滚动到的元素包装到…
中,然后当您需要滚动时,只需将焦点设置在上,即本机JS、跨浏览器、平滑滚动(更新2020)
设置ScrollTop
会给出所需的结果,但scr