JQuery使用mouseX百分比隐藏/显示

时间:2015-08-06 18:27:06

标签: javascript jquery html css

我确定这非常简单,我很接近(ish。)我试图在基于鼠标的10个div(一次只显示一个)之间切换。 X位置。

目前我已将鼠标的X位置转换为百分比,并将其用作变量,根据光标的距离显示/隐藏元素,但是我可以使用它来显示/隐藏元素。我无法弄清楚如何管理10个元素,因此一次只能显示一个元素。

这里是fiddle

谢谢!

//Look at mouse
$(document).mousemove(function(e) {
    // Set a variable (perc) X mouse position in pixels divide by the browser size times by 100
    var perc = e.pageX / $(document).width() * 100;

    // If that perc is less than 20 and higher than 10
    if (perc > 20 && perc < 30) {
        // show flick span
        $('#flick1').show();
    }
    else {
        // or hide flick span
        $('#flick1').hide();
    }
});

2 个答案:

答案 0 :(得分:1)

这应该这样做:

$(document).mousemove(function (e) {
    $spans = $("span[id^=flick]").removeClass("desc");
    var perc = Math.floor(e.pageX / $(document).width() * $spans.length);
    $spans.hide().eq(perc).show();
});
.desc {
    display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>
    <span id="flick1">word 1</span>
    <span class="desc" id="flick2">word 2</span>
    <span class="desc" id="flick3">word 3</span>
    <span class="desc" id="flick4">word 4</span>
    <span class="desc" id="flick5">word 5</span>
    <span class="desc" id="flick6">word 6</span>
    <span class="desc" id="flick7">word 7</span>
    <span class="desc" id="flick8">word 8</span>
    <span class="desc" id="flick9">word 9</span>
    <span class="desc" id="flick10">word 10</span>
</h1>

答案 1 :(得分:1)

我刚看到问题已经解决了,但我仍然想展示我的解决方案:

在你的头部:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JS:

//Look at mouse
$(document).mousemove(function(e){
    //Set a variable (perc) X mouse position in pixels divide by the browser size times by 100
    var perc = e.pageX / $(document).width() * 100;
    //If that perc between 0 and 100 (whole page)
    if (perc > 0 && perc < 100) {
        //show flick span
        for (var i=1; i<11; i++){
           $('#flick'+i).hide();            
        }
        //round the number
        var nr = Math.round(perc/10);
        $('#flick'+nr).show();
        $('#flick'+nr).removeClass('desc');
    }
    else {
        //Hide all flicks
        for (var i=1; i<11; i++){
           $('#flick'+i).hide();            
        }
    }
});

Fiddle

快乐编码:)