javascript - 获取一组背景图像以供以后保存,然后在它们和背景颜色之间悬停切换
问题描述
这是我的问题:
我创建了一个如下所示的块:
<div class="col-md-4">
<a href="/our-difference/our-story/"><p></p>
<div class="img-link" style="background-image: url(/wp-content/uploads/2016/07/our_story_600x400-1.jpg)">
<div class="text">
<h2>Our Story</h2>
<h3>For over 25 years we have specialized in and excelled at health care and human services education.</h3>
</div>
</div>
</a>
</div>
CSS:
.img-link {
position: relative;
width: 100%;
height: 200px;
background-size: cover;
&:hover {
opacity: .9;
}
.text {
position: absolute;
top: 10px;
}
}
我的问题是我必须以友好的方式设置 HTML,因为它是 WordPress,所以我必须内联添加背景图像。
我的目标如下:
当用户将鼠标悬停在背景图像所在的 div 上时,颜色将变为具有不透明度的实际颜色,并且文本不会受到影响(就像使用 opacity 属性时应该发生的那样)。
但是如果我使用 mouseOut 和 mouseOver,例如:
$('.img-link')
.mouseover(function(){
$(this).css('background', 'green');
})
.mouseout(function(){
$(this).css('background', 'initial');
});
当用户离开图像时,背景将恢复为初始图像,此时该图像将为空。
前:
background-image: url(/wp-content/uploads/2016/07/our_story_600x400-1.jpg);
后
background-color: #9b7878a8.
在最后一步中,背景将为空。
我的问题是:有没有办法“保存”背景图像(如在数组中),然后使用数组的值重新应用原始背景图像?
就像是:
let arrayimage = $('.img-link');
$('.img-link')
.mouseover(function(){
$(this).css('background', 'green');
})
.mouseout(function(){
$(this).css('background', arrayimage);
})
这只是一个例子,代码距离正确,我是新手。
解决方案
看到您正在使用 jQuery,这实际上非常简单,并且假设您只有一个要存储的背景图像,则根本不需要数组。
$(document).ready(function(){
var imgBackground = $('.img-link').css('background-image');
$('.img-link').mouseover(function(){
$(this).css('background', 'green');
}).mouseout(function(){
$(this).css('background', imgBackground);
});
});
在这里,开始$(document).ready()
确保在执行任何其他操作之前加载您的内联图像。然后,我们可以使用 jQuery 函数将加载的图像安全地存储在一个变量中.css()
,告诉它检索背景图像。在鼠标移出时,您需要做的就是将该变量重新分配为图像。
如果您需要删除url(...)
图片链接周围的内容,您可以在此处查看包含该信息的另一个类似答案:我可以获取 div 的背景图片网址吗?
推荐阅读
- java - 如何使用循环中生成的线程进行多线程处理?
- azure-pipelines - 在 Azure DevOps 服务器中使用私有 Azure 工件中的包
- c# - 您可以仅使用列表 ID 将动态模板发送到列表吗?
- c# - 在unity / c#中选择对象时如何播放正确的声音
- html - 引导卡在 bootstrapemail 中不起作用
- python-3.x - 从生成器创建 numpy 数组,列表列表
- vue.js - nuxt如何生成动态路由
- android-studio - 使用切换按钮打开和关闭 TextToSpeech?
- for-loop - 遍历嵌套字典并将键值为 True 的实例合并到打印语句中
- c++ - 在 C++ 中找到二叉树中的最大高度路径