2016-08-24 172 views
0

我想在左鍵單擊鼠標事件時顯示上下文菜單,目前在我的示例中它正在右鍵單擊。如果我再次點擊其他地方,它應該隱藏。我怎樣才能做到這一點??如何打開D3.js上下文菜單左鍵單擊而不是右鍵點擊

呦還可以在這裏看到我的代碼在jsFiddle

var data = [{ 
 
    text: 'Apple', 
 
    icon: 'https://i.stack.imgur.com/5mrSI.jpg?s=32&g=1' 
 
}, { 
 
    text: "Orange", 
 
    icon: 'https://i.stack.imgur.com/5mrSI.jpg?s=32&g=1', 
 
}, { 
 
    text: "Banana", 
 
    icon: 'https://i.stack.imgur.com/5mrSI.jpg?s=32&g=1' 
 
}, { 
 
    text: "Grape", 
 
    icon: 'https://i.stack.imgur.com/5mrSI.jpg?s=32&g=1' 
 
}]; 
 

 
var svgContainer = d3.select("body") 
 
    .append("svg") 
 
    .attr("width", 200) 
 
    .attr("height", 200); 
 

 
var circle = svgContainer 
 
    .append("circle") 
 
    .attr("cx", 30) 
 
    .attr("cy", 30) 
 
    .attr("r", 20) 
 
    .on('contextmenu', function(d, i) { 
 
    // create the div element that will hold the context menu 
 
    d3.selectAll('.context-menu').data([1]) 
 
     .enter() 
 
     .append('div') 
 
     .attr('class', 'context-menu'); 
 
    // close menu 
 
    d3.select('body').on('click.context-menu', function() { 
 
     d3.select('.context-menu').style('display', 'none'); 
 
    }); 
 
    // this gets executed when a contextmenu event occurs 
 
    d3.selectAll('.context-menu') 
 
    \t .html('') 
 
     .append('ul') 
 
     .selectAll('li') 
 
     .data(data) 
 
     .enter() 
 
     .append('li') 
 
     .append(function(d) { 
 
     const icon = document.createElement('img'); 
 
     icon.src = d.icon; 
 

 
     return icon; 
 
     }) 
 
     .select(function() { 
 
     \t return this.parentNode; 
 
    \t }) 
 
     .append('span') 
 
     .text(function (d) { 
 
     \t return d.text; 
 
     }) 
 
     .on('click', function(d) { 
 
     }); 
 

 
    d3.select('.context-menu').style('display', 'none'); 
 
    // show the context menu 
 
    d3.select('.context-menu') 
 
     .style('left', (d3.event.pageX - 2) + 'px') 
 
     .style('top', (d3.event.pageY - 2) + 'px') 
 
     .style('display', 'block'); 
 
    d3.event.preventDefault(); 
 
    });
.context-menu { 
 
    position: absolute; 
 
    display: none; 
 
    background-color: #f2f2f2; 
 
    border-radius: 4px; 
 
    font-family: Arial, sans-serif; 
 
    font-size: 14px; 
 
    min-width: 150px; 
 
    border: 1px solid #d4d4d4; 
 
    z-index: 1200; 
 
} 
 

 
.context-menu ul { 
 
    list-style-type: none; 
 
    margin: 4px 0px; 
 
    padding: 0px; 
 
    cursor: default; 
 
} 
 

 
.context-menu ul li { 
 
    padding: 4px 16px; 
 
} 
 

 
.context-menu ul li:hover { 
 
    background-color: #4677f8; 
 
    color: #fefefe; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

回答

0

如果更改的jsfiddle行:

.on('contextmenu', function(d, i) { 

.on('mousedown', function(d, i) { 

您應該看到該操作的彈出窗口。我注意到你在那裏有一些其他的click和preventDefault()調用,所以這些可能與點擊事件相沖突。