ОБНОВЛЕНИЕ . Я обновил фрагмент кода, включив в него всю страницу, как в Firebug.
У меня такой код:
<html><head>
<title>Welcome to CodeIgniter</title>
<!--[if IE]>
<script type="text/javascript" src="/assets/js/Jit/Extras/excanvas.js"></script>
<![endif]-->
<script src="/assets/js/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="/assets/js/Jit/jit.js" type="text/javascript"></script>
<script src="/assets/js/tree.js" type="text/javascript"></script>
<script src="/assets/js/jquery/jquery.rightClick.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".node").rightClick(function() {
alert ("RIGHT CLICK");
});
$.getJSON("/ajax/fetch/tree", function(data) {
init(data);
});
});
$(".node").live("click", function() {
alert ($(this).attr("id"));
});
</script>
<style type="text/css">
html, body {
width:100%;
height:100%;
background-color:#444;
text-align:center;
overflow:hidden;
font-size:9px;
font-family:Verdana, Geneva, Arial, Helvetica, sans-serif;
margin:0;padding:0;
}
/* visualization style container */
#infovis {
background-color:#222;
position:relative;
width:900px;
height:500px;
}
a, a:link, a:visited {
color:#343439;
}
/* spacetree nodes CSS class */
.node {
background-color:transparent;
font-weight:bold;
overflow:hidden;
text-decoration:none;
position:absolute;
text-align:center;
padding:4px 1px 1px 1px;
}
.node:hover {
color:#393434;
}
.hidden{
display:none;
}
</style>
</head><body>
<div id="infovis">
<div id="mycanvas" style="width: 900px; height: 500px; position: relative;">
<canvas id="mycanvas-canvas" width="900" height="500" style="position: absolute; top: 0pt; left: 0pt; width: 900px; height: 500px;"></canvas>
<div id="mycanvas-label" style="overflow: visible; position: absolute; top: 0pt; left: 0pt; width: 900px; height: 0pt;">
<div id="1" class="node" style="position: absolute; width: 60px; height: 17px; cursor: pointer; color: rgb(51, 51, 51); font-size: 0.8em; text-align: center; padding-top: 3px; left: 200px; top: 265px;">0.0</div>
<div id="4" class="node" style="position: absolute; width: 60px; height: 17px; cursor: pointer; color: rgb(51, 51, 51); font-size: 0.8em; text-align: center; padding-top: 3px; left: 420px; top: 215px;">2.0</div>
<div id="5" class="node" style="position: absolute; width: 60px; height: 17px; cursor: pointer; color: rgb(51, 51, 51); font-size: 0.8em; text-align: center; padding-top: 3px; left: 420px; top: 240px;">2.1</div>
<div id="9" class="node" style="position: absolute; width: 60px; height: 17px; cursor: pointer; color: rgb(51, 51, 51); font-size: 0.8em; text-align: center; padding-top: 3px; left: 420px; top: 265px;">2.2</div>
<div id="10" class="node" style="position: absolute; width: 60px; height: 17px; cursor: pointer; color: rgb(51, 51, 51); font-size: 0.8em; text-align: center; padding-top: 3px; left: 420px; top: 290px;">2.3</div>
<div id="2" class="node" style="position: absolute; width: 60px; height: 17px; cursor: pointer; color: rgb(51, 51, 51); font-size: 0.8em; text-align: center; padding-top: 3px; left: 310px; top: 253px;">1.0</div>
<div id="6" class="node" style="position: absolute; width: 60px; height: 17px; cursor: pointer; color: rgb(51, 51, 51); font-size: 0.8em; text-align: center; padding-top: 3px; left: 640px; top: 275px; display: none;">3.0</div>
<div id="3" class="node" style="position: absolute; width: 60px; height: 17px; cursor: pointer; color: rgb(51, 51, 51); font-size: 0.8em; text-align: center; padding-top: 3px; left: 310px; top: 278px;">1.1</div>
<div id="8" class="node" style="position: absolute; width: 60px; height: 17px; cursor: pointer; color: rgb(51, 51, 51); font-size: 0.8em; text-align: center; padding-top: 3px; left: 530px; top: 228px;">5.0</div>
<div id="11" class="node" style="position: absolute; width: 60px; height: 17px; cursor: pointer; color: rgb(51, 51, 51); font-size: 0.8em; text-align: center; padding-top: 3px; left: 530px; top: 253px;">5.1</div>
</div>
</div>
</div>
<div class="node">HELLO WORLD!</div>
</body></html>
Я хочу иметь возможность щелкнуть правой кнопкой мыши по одному из элементов div с помощью класса "node", а затем запустить событие. Есть ли способ сделать это с помощью jQuery? Я посмотрел на плагин jQuery контекстного меню, расположенный на http://www.javascripttoolbox.com/lib/contextmenu /. Однако, если я использую $ ('node'). ContextMenu (...), это не сработает. Если я использую $ ('infovis'). ContextMenu (...), контекстное меню работает.
Похоже, что эти div на самом деле за пределами холста. Я вытащил этот код прямо из Firebug.
3 ответа
Попробуй это:
$(document).ready(function(){
$(document)[0].oncontextmenu = function() {return false;}
$("#infovis").delegate('.node','mousedown',function(e){
if( e.button == 2 ) {
e.stopPropagation()
alert('Right mouse button!');
return false;
} else {
return true;
}
});
});
Я предполагаю, что #infovis виден с самого начала, и вы используете javascript, чтобы заполнить этот div div .node. Таким образом, вы хотите использовать делегирование событий, поэтому вы привязываетесь не к каждому узлу, а к родительскому узлу. Это делает ваш код быстрее, даже если у вас есть 1000 .nodes. Кроме того, вам не нужно помещать привязки в обратный вызов.
Мы делегируем mousedown и фиксируем событие, если кнопка == 2 (кнопка правой кнопки мыши).
Также вы отключаете поведение правой кнопки мыши по умолчанию, останавливая событие contextmenu.
Сообщите мне, если это сработает для вас.
Попробуйте этот код:
$("#infovis").delegate('.node', 'mousedown', function(e) {
if (e.button == 2) {
e.stopPropagation()
console.log(e.target.id);
console.log(e.target.textContent);
return false;
} else {
return true;
}
});`
e.target
возвращает общее количество div, которые содержат class = "node"
e.taget.textcontext
возвращает имя узла в элементе div
Вы пробовали плагин jquery.rightClick? Кажется, я работал над быстрым тестом:
http://abeautifulsite.net/blog/2008/05/jquery-right-click-plugin/
$('.node').rightClick(function() {
console.log('right click');
});
Похоже, он довольно старый, но опять же там не так много кода. Я думаю, что это может потребовать небольшого обновления, но не так много.
Похожие вопросы
Новые вопросы
javascript
По вопросам программирования на ECMAScript (JavaScript / JS) и его различных диалектах / реализациях (кроме ActionScript). Включите все соответствующие теги в свой вопрос; например, [node.js], [jquery], [json] и т. д.