jQuery在元素悬停上鼠标旁边显示图像

时间:2017-05-18 02:50:59

标签: javascript jquery html css hover

我在表格中有一列元素,基本上是:

__________________
Element 1 | data1
Element 2 | data2
Element 3 | data3
Element 4 | data4
Element 5 | data5

每个data都有一个图片,存储为属性data-source

我试图获取功能,当用户将鼠标悬停在data1data2,... data5上时,它会显示鼠标旁边的图像用那个元素。

我面临的问题是,大约80%的时间图像会显示在正确的位置,另外20%会显示在最后一张图像的位置。这不会起作用,因为图像的大小会有所不同。

我还注意到当悬停在元素上时,显示图像时会有很多闪烁(如果你移动鼠标但仍悬停在元素上)。

这是我的代码:

HTML:

<tbody class="task-group">
    <tr class="row-major row">
        <td class="col-lg-2 points-col-major">0</td>
        <td class="col-lg-1 proof-col-major spreadsheet-proof no-pad">
            <label for="file-proof-4" class="text-center non-bold proof-none proof-thumbnail" style="width:77px;line-height:39px;margin:0;">None</label>
            <input type="file" id="file-proof-4" accept="image/jpg, image/jpeg, image/png" style="display:none;width:77px;">
        </td>
    </tr>
    <tr class="row-minor row">
        <td class="col-lg-2 points-col-minor">0</td>
        <td class="col-lg-7 task-col-minor">Test col</b></td>
        <td class="col-lg-1 proof-col-minor spreadsheet-proof no-pad">
            <label for="file-proof-5" class="text-center non-bold proof-none proof-thumbnail" style="width:77px;line-height:39px;margin:0">None</label>
            <input type="file" id="file-proof-5" accept="image/jpg, image/jpeg, image/png" style="display:none;width:77px;">
        </td>
    </tr>
</tbody>

<div id="spreadsheet-image-thumbnail-container">
    <img id="spreadsheet-image-thumbnail">
</div>

JS:

// Show image on hover
$(".spreadsheet-proof > .proof-thumbnail").on({

    // handlerIn
    mouseenter: function(e) {
        $("#spreadsheet-image-thumbnail").attr("src", "/assets/img/user_uploaded_images/" + $(this).attr("data-proof-source"));

        var proofImage = document.getElementById("spreadsheet-image-thumbnail");
        console.log(e.clientX);
        console.log(proofImage.naturalWidth);
        console.log(e.clientX - proofImage.naturalWidth + 30);
        var x = (e.clientX - proofImage.naturalWidth + 30) + 'px';
        var y = (e.clientY) + 'px';

        $("#spreadsheet-image-thumbnail-container").css({
            "left": x,
            "top": y,
        });
        $("#spreadsheet-image-thumbnail").show();
        $("#spreadsheet-image-thumbnail-container").show();
    },
    // handlerOut
    mouseleave: function() {
        $("#spreadsheet-image-thumbnail-container").hide();
        $("#spreadsheet-image-thumbnail").hide();
    }
});

CSS:

#spreadsheet-image-thumbnail-container {
    position: fixed;
    border: 1px solid #333;
    padding: 5px;
    border-radius: 5px;
    background-color: #000;
}

我希望图像以这种方式出现在光标旁边:

将鼠标悬停在元素5上:

enter image description here

将鼠标悬停在元素2上:

enter image description here

感谢任何帮助!

0 个答案:

没有答案