我有一个div,每次用鼠标滚轮滚动时,它都会膨胀10%。问题是它从左角开始膨胀。我怎样才能从中间展开呢?
我一直在寻找解决办法,但我找到的答案与动画有关。
HTML格式
<body>
<div id="holder" />
</body>
JS公司
zoom = value => {
let size = value;
return {
up: () => {
size += 10;
holder.style.height = `${size}%`;
holder.style.width = `${size}%`;
},
down: () => {
size -= 10;
holder.style.height = `${size}%`;
holder.style.width = `${size}%`;
}
}
}
zoom = zoom(100);
document.onmousewheel = event => {
(event.wheelDelta > 0) ? zoom.up() : zoom.down();
}
CSS
body {
background-color: rgb(33, 37, 43);
align-content: center;
overflow: hidden;
}
#holder {
height:100%;
width: 100%;
margin: auto;
background: url("some-image.jpg") no-repeat center/contain;
}
var zoom = value => {
let size = value;
return {
up: () => {
size += 10;
holder.style.height = `${size}%`;
holder.style.width = `${size}%`;
},
down: () => {
size -= 10;
holder.style.height = `${size}%`;
holder.style.width = `${size}%`;
}
}
}
zoom = zoom(100);
document.onmousewheel = event => {
(event.wheelDelta > 0) ? zoom.up() : zoom.down();
}
.body {
background-color: rgb(33, 37, 43);
align-content: center;
overflow: hidden;
}
#holder {
height:100%;
width: 100%;
margin: auto;
background: url("http://placehold.it/300x300") no-repeat center/contain;
}
<div class="body">
<div id="holder" />
</div>
最佳答案
如果flexbox
是一个选项,您可以将display: flex
添加到body
中-请参见下面的演示:
zoom = value => {
let size = value;
return {
up: () => {
size += 10;
holder.style.height = `${size}%`;
holder.style.width = `${size}%`;
},
down: () => {
size -= 10;
holder.style.height = `${size}%`;
holder.style.width = `${size}%`;
}
}
}
zoom = zoom(100);
document.onmousewheel = event => {
(event.wheelDelta > 0) ? zoom.up(): zoom.down();
}
body {
background-color: rgb(33, 37, 43);
align-content: center;
overflow: hidden;
display: flex; /* ADDED */
height: 100vh; /* initial height*/
}
#holder {
height: 100%;
width: 100%;
margin: auto;
background: url("http://placehold.it/100x100") no-repeat center/contain;
}
<div id="holder" />
另一种方法是定位——见下文:
zoom = value => {
let size = value;
return {
up: () => {
size += 10;
holder.style.height = `${size}%`;
holder.style.width = `${size}%`;
},
down: () => {
size -= 10;
holder.style.height = `${size}%`;
holder.style.width = `${size}%`;
}
}
}
zoom = zoom(100);
document.onmousewheel = event => {
(event.wheelDelta > 0) ? zoom.up(): zoom.down();
}
body {
background-color: rgb(33, 37, 43);
align-content: center;
overflow: hidden;
height: 100vh; /* initial height*/
}
#holder {
height: 100%;
width: 100%;
margin: auto;
background: url("http://placehold.it/100x100") no-repeat center/contain;
/* ADDED THESE */
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
<div id="holder" />