簡體   English   中英

通過鼠標指針的位置更改來更改文本?

[英]Changing text with position change of mouse pointer?

我正在嘗試編寫一個腳本,該腳本要放在我的html網站中。 該腳本的作用是隨着鼠標光標位置的變化來更改文本。 例如。 如果用戶打開(x,y)=(1,1),則將顯示一些文本,而如果打開(x,y)=(2,2),則將顯示其他一些隨機文本。

var text = [ 'I am human.']

我不確定如何將其連接到鼠標事件。 就像指針移動一樣,顯示文本列表中的任何隨機文本。 任何人都可以提供代碼嗎? 真的會幫助我。 謝謝!

mousemove綁定在window或其他物體上,然后在事件對象上使用screenX / screenY / clientX / clientY / clientY

一個簡單的演示:

var $message = $('#message');

$(window).on('mousemove', function(e) {
    if(e.clientX > e.clientY) {
        $message.text('top right triangle');
    } else {
        $message.text('bottom left triangle');
    }
});

HTML:

<div id="message">Move the mouse.</div>

http://jsfiddle.net/qjtnd/

由於使用的是JQuery,因此可以只使用鼠標移動功能 ,如果需要效果,可以使用JQuery的animate

Javascript:

$(document).mousemove(function(){
   var randText = text[Math.floor(Math.random()*text.length)];
   var div = $("#textDiv");
   div.stop().animate({"opacity": "0"}, 100, function(){
       $(this).html(randText);
       $(this).stop().animate({"opacity": "1.0"}, 100);
   });
});

HTML:

<div id="textDiv"></div>
var text = [ 'I am human.'
            , 'Some text here.'
            , 'I love technology.'
            , 'You are a good person'
            ]
$(document).mousemove(function(event) {
   var randomItem = text[Math.floor(Math.random()*text.length)];
    alert(randomItem);
});

參見http://jsfiddle.net/2raaa/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM