2013-09-24 8 views
12

D3에서 렌더링 한 SVG 그래픽의 미국 주와 카운티의지도가 있습니다. 각 패스에는 mouseover, mouseout 및 click 이벤트가 바인딩되어 있으며 경로 ID로 설정된 FIPS 카운티 코드가 있습니다.d3 - 트리거 mouseover 이벤트

사용자가 주 또는 카운티의 이름을 입력 할 수있는 jQuery 자동 완성 입력이 있습니다. 해당 FIPS ID를 사용할 수있게하는 입력을 감안할 때 프로그래밍 방식으로 mouseover 이벤트를 트리거하려면 어떻게해야합니까?

답변

2

구조체에서 mouseover 이벤트가 javascript 함수를 호출하고 원하는 때에 언제든지 같은 함수를 호출 할 수 있도록 javascript를 구조화하십시오.

7

나는 대답을 알아 냈다. 주된 문제는 D3에는 jQuery처럼 명시적인 trigger 함수가 없다는 것입니다. 그러나이를 시뮬레이션 할 수 있습니다.

d3.json("us-counties.json", function(json){ 

    thisObj._svg.selectAll("path") 
    .data(json.features) 
    .enter().append("path") 
    .attr("d", thisObj._path) 
    .attr("class", "states") 
    .attr("id", function(d){ 
     return d.id; //<-- Sets the ID of this county to the path 
    }) 
    .style("fill", "gray") 
    .style("stroke", "black") 
    .style("stroke-width", "0.5px") 
    .on("dblclick", mapZoom) 
    .on("mouseover", mapMouseOver) 
    .on("mouseout", mapMouseOut); 
}); 

를 통해 구축 된 D3 경로와

var mapMouseOver(d){ 

    d3.selectAll($("#" + d.id)) 
    .style("fill", "red") 
    .style("stroke", "blue"); 

} 

는 일반적으로 대부분의 튜토리얼이 사용하는 말을 채우기 및 스트로크 색상을 변경하는 마우스 오버 이벤트 핸들러가 말

d3.select(this)... 

하지만 실제로이 값을 사용하면 효과가 있습니다. 당신이 당신에게 노드의 ID를 취득하는 이벤트 핸들러를 가지고 있고,

를 통해 그것을 실행할 경우
$("#someDropdownSelect").change(someEventHandler) 

function someEventHandler(){ 

    //get node ID value, sample 
    var key = $(this) 
       .children(":selected") 
       .val(); 

    //trigger mouseover event handler 
    mapMouseOver({id : key}); 

} 

가 드롭 다운 선택에 따라 마우스 오버 이벤트를 실행합니다

5

사용자가 직접 이벤트에 파견하여이 작업을 수행 할 수 있습니다 원하는 요소 :

var event = document.createEvent('SVGEvents'); 
event.initEvent(eventName,true,true); 
element.dispatchEvent(event); 

가에서 자세한 내용을 참조하십시오이 blog post

+0

완벽하게 작동합니다. –

2

스티브 Greatrex의 솔루션이 될 때까지 나를 위해 일 iOS 9는 아니지만 iOS 10은 지원하지 않습니다.

내 코드와 일부 연구를 디버깅 한 후 createEvent 및 initEvent 함수가이 documentation에 따라 사용되지 않는 것으로 보입니다.

이 글을 쓰는의 새로운 방법은 다음과 같습니다 작성 및 이벤트 생성자 이벤트를 트리거의 새로운 방법에 대한

var event = new MouseEvent('SVGEvents', {}); 
element.dispatchEvent(event); 

자세한 설명은 here를 찾을 수 있습니다.