html - 是否可以使用 html 中的 img 标签来做视差效果,还是必须由背景来做?
问题描述
我是处理css / html的新手,我试图做一些边界半径中包含的视差效果,但每次我尝试使用背景(url)做它似乎并没有做我想要的,所以我想知道是否可以从 img 标签中做到这一点?
解决方案
您可以使用 JS 解决您的问题。看看下面的例子。它会为你工作。祝你今天过得愉快。
$('.img-parallax').each(function() {
var $image = $(this);
var $imageParent = $(this).parent();
function parallaxImg () {
var speed = $image.data('speed');
var imageY = $imageParent.offset().top;
var winY = $(this).scrollTop();
var winH = $(this).height();
var parentH = $imageParent.innerHeight();
// The next pixel to show on screen
var winBottom = winY + winH;
// If block is shown on screen
if (winBottom > imageY && winY < imageY + parentH) {
// Number of pixels shown after block appear
var imgBottom = ((winBottom - imageY) * speed);
// Max number of pixels until block disappear
var imgTop = winH + parentH;
// Percentage between start showing until disappearing
var imgPercent = ((imgBottom / imgTop) * 100) + (50 - (speed * 50));
}
$image.css({ top: imgPercent + '%', transform: 'translate(-50%, -' + imgPercent + '%)' });
}
$(document).on({
scroll: function () {
parallaxImg();
}, ready: function () {
parallaxImg();
}
});
});
@import url(https://fonts.googleapis.com/css?family=Amatic+SC:400,700);
html,
body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
font-family: "Amatic SC", cursive;
}
.block {
width: 100%;
height: 100%;
position: relative;
overflow: hidden;
font-size: 16px;
}
.block h2 {
position: relative;
display: block;
text-align: center;
margin: 0;
top: 50%;
transform: translateY(-50%);
font-size: 10vw;
color: white;
font-weight: 400;
}
.img-parallax {
width: 100vmax;
z-index: -1;
position: absolute;
top: 0;
left: 50%;
transform: translate(-50%, 0);
pointer-events: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="block">
<img src="https://unsplash.it/1920/1920/?image=1003" data-speed="-1" class="img-parallax">
<h2>Parallax 1</h2>
</div>
<div class="block">
<img src="https://unsplash.it/1920/1920/?image=1002" data-speed="1" class="img-parallax">
<h2>Parallax 2</h2>
</div>
<div class="block">
<img src="https://unsplash.it/1920/1920/?image=1014" data-speed="1" class="img-parallax">
<h2>Parallax 3</h2>
</div>
推荐阅读
- node.js - NodeJS IBM Watson - 返回整数
- material-ui - Material-UI 数据网格样式
- bash - 使用 grep xargs sed 更有效地在文件中重新生成 UUID
- c - Valgrind memcpy 大小为 8 的无效写入 (uintptr_t *)
- python - 自动化无聊的东西 - Collatz 序列
- python - 如何从特定值类型中获取平均值?
- python - 如何在 Gitlab CI/CD 管道中使用 Docker-Compose 运行 API 端点测试
- javascript - Javascript 地图对象文字不起作用,但 new Object() 有效
- apache-spark - S3 中针对 Athena Hive Hudi 对象的 Redshift 查询错误——频谱扫描错误:断言代码:15005
- eclipse - PyDev 说来自导入的未定义变量:AF_INET