javascript - 鼠标移动目标上的 jQuery 选择所有相似的元素

标签 javascript jquery css background-position onmousemove

我有(例如)6 个元素,所有元素都具有相同的类和不同的内容。它们都有稍微放大的背景。当鼠标悬停在它们上面时,我需要它们的背景相应地移动。我的问题 - 一旦我将鼠标悬停在单个元素上,所有背景都会移动。有什么帮助吗?
这是我的代码:

HTML(单个元素):

<a href="/" class="project" style="background-image: url('link_to_image');"><p>Project</p><span>Description</span></a>

CSS(同样是单个元素):

.project {
    position: relative;
    display: inline-block;
    margin: 10px;
    height: 400px;
    width: 400px;
    background: #b0bec5;
    color: #fff;
    text-decoration: none;
    box-shadow: inset 0px 0rem 0px rgba(0,0,0,0), inset 0px -50px 100px -40px rgba(0,0,0,0.6);
    transition: box-shadow .5s ease-in-out;
    overflow: hidden;
    float: left;
    white-space: initial;
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
}

.project p {
    position: absolute;
    bottom: 2%;
    left: 2%;
    font-size: 40px;
    font-family: "Josefin Slab";
    font-weight: bold;
    transition: all .46s ease-in-out;
    transition-delay: .02s;
    z-index: 1;
}

.project span {
    display: block;
    position: absolute;
    top: 100%;
    left: 2%;
    font-size: 20px;
    font-family: "Raleway";
    transition: all .46s ease-in-out;
    transition-delay: .02s;
    z-index: 1;
}

.project:hover p {
    bottom: 88%;
}

.project:hover span {
    top: 15%;
}

.project:hover {
    box-shadow: inset 0px -30rem 0px rgba(0,0,0,0.4);
}

JS:

$(".project").on("mousemove", function(e){
    x = (e.pageX - e.target.offsetLeft * 1.5) / 4;
    console.log(x);
    $(".project").css('background-position-x', x + 'px');
});

最佳答案

使用这个!

$(".project").on("mousemove", function(e){
    x = (e.pageX - e.target.offsetLeft * 1.5) / 4;
    console.log(x);
    $(this).css('background-position-x', x + 'px'); //"this" refers to the .project elem that the event is occurring on.
});

关于javascript - 鼠标移动目标上的 jQuery 选择所有相似的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26430910/

相关文章:

php - 如何防止多个嵌套 SQL 查询之间出现重复输出?

javascript - 在页面加载之前运行模块脚本?

javascript - 使用数组搜索元素的数据属性并将其隐藏

html - 为什么我的元素标签不影响链接?正确的语法?

javascript - 如何在javascript中获取内部div的值

javascript - 我如何编写一个 CouchDB View 来列出每个存储文档的大小?

javascript - Sequelize 关联函数不可用 - IntellIj 问题

javascript - 抓取指定的图像源并将其添加到输入表单中

html - css 导航栏位置固定不工作

css - Extjs fieldset - 折叠时删除标题后的行