如何将滚动条设置在滚动条的中心



我正在使用react应用程序并尝试显示图像并应用自定义放大/缩小。没有使用任何库,因为我必须在每个图像上添加标记,并且使用库进行缩放不会为定位标记提供适当的坐标。

我将max-height和max-width传递给图像,以便图像可以以其原始比例查看。放大和缩小功能:

zoomOut = () => {
var myImg = document.getElementById("action-image")
var currWidth = (myImg.style.maxWidth.split("v"))[0];
var currHeight = (myImg.style.maxHeight.split("v"))[0];
myImg.style.maxWidth = (Number(currWidth) - 50) + "vw";
myImg.style.maxHeight = (Number(currHeight) - 50) + "vh";
if (this.state.scale == 0)
this.resetImage()
else if (this.state.scale != 0) {
this.setState((state) => ({
...state,
scale: this.state.scale - 1
}))
}
}
zoomIn = () => {
console.log(this.state.scale);
if (this.state.scale < 11) {
var myImg = document.getElementById("action-image")
var currWidth = (myImg.style.maxWidth.split("v"))[0];
var currHeight = (myImg.style.maxHeight.split("v"))[0];
myImg.style.maxWidth = (Number(currWidth) + 50) + "vw";
myImg.style.maxHeight = (Number(currHeight) + 50) + "vh";
this.setState((state) => ({
...state,
scale: this.state.scale + 1
}))
}
}
resetImage = () => {
var myImg = document.getElementById("action-image")
myImg.style.maxHeight = '95vh'
myImg.style.maxWidth = '75.4vw'
this.setState((state) => ({
...state,
scale: 0,
}))
}

图像呈现:

<RegionSelect
maxRegions={1}
regions={this.state.imageLoad ? [] : this.state.regions}
regionStyle={regionStyle}
constraint={false}
onChange={this.onChange}
Draggable={false}
regionRenderer={this.regionRenderer}
>
<img id="action-image" style={{ zIndex: 1, maxHeight: '95vh', maxWidth: '75.4vw' }} 
src={this.state.imageURL} onLoad={((load) => {
this.setState((state) => ({
...state,
imageLoad: false,
height: 'unset',
width: 'unset'
}))
})} />
</RegionSelect>

放大前图像

放大后的图像

问题是,当图像集中以保持其宽高比时,当图像放大时,滚动条也应该集中,这将允许向上滚动。但是滚动条从最顶端开始&最左边的位置,使图像的某些部分(从顶部和左侧)隐藏。

首先你需要得到滚动条拇指的高度然后可以使用window.scroll函数来设置所需的距离为什么我们需要滚动条拇指的高度?因为scroll函数不会根据它的中心移动滚动条

var arrowHeight = 25;
var viewportHeight = window.innerHeight;
var contentHeight = getComputedStyle(document.body).height;
contentHeight = parseFloat(contentHeight);
var viewableRatio = viewportHeight / contentHeight;
var scrollBarArea = viewportHeight - arrowHeight * 2; 
var thumbHeight = scrollBarArea * viewableRatio; 
var scrollAmount = (contentHeight / 2) - thumbHeight;
window.scroll({
top: scrollAmount,
left: 0,
behavior: 'smooth'
})

这里是完整的小提琴,看看它是如何工作的

https://jsfiddle.net/mahdiar_mansouri/5ypaeo4q/5/

最新更新