在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/室內(nèi)設(shè)計(jì)/ svg中怎么獲得鼠標(biāo)指針的相對(duì)位置

svg中怎么獲得鼠標(biāo)指針的相對(duì)位置

用svg畫了一個(gè)1000寬度的矩形, 我想鼠標(biāo)移動(dòng)時(shí)獲得指針在矩形中的相對(duì)位置,請(qǐng)問要怎么編寫?

比如水平移動(dòng)到中間, x就是500這樣子, 代碼如下:

<svg version="1.1" baseProfile="full" width="100%" height="200" viewBox="0 0 1020 200"
xmlns="http://www.w3.org/2000/svg" style="border: 1px solid red">
  <g transform="translate(10,0)">
    <rect x="0" width="1000" height="90%" fill="#33546F" onMouseMove="handleMouseMove(evt)" />
    <line x1="100" x2="100" y1="0" y2="90%" stroke="#ccc" id="line" />
  </g>
</svg>

測(cè)試代碼地址
http://jsrun.net/kdgKp/edit

回答
編輯回答
乞許

你得對(duì)一個(gè)不變的元素進(jìn)行鼠標(biāo)事件監(jiān)聽,不然不亂套了

function handleMouseMove(event) {
  // console.log(evt)
  const width = document.getElementById('container').scrollWidth;
  const offsetX = event.offsetX


  console.log(width,offsetX,event)
  document.getElementById('rect').setAttribute('x',offsetX/width*1000)
  // const im = evt.target.getScreenCTM();
  // const svg = evt.target.ownerSVGElement;
  // const pt = svg.createSVGPoint();
  // pt.x = evt.clientX;
  // pt.y = evt.clientY;
  // const p = pt.matrixTransform(im);
  // console.log(p.x, p.y);
}
<svg version="1.1" baseProfile="full" width="100%" height="200" viewBox="0 0 1020 200"
xmlns="http://www.w3.org/2000/svg" style="border: 1px solid red" id="container" onmousemove="handleMouseMove(event)">
  <g transform="translate(10,0)">
    <rect id="rect" x="0" width="1000" height="90%" fill="#33546F"/>
    <line x1="100" x2="100" y1="0" y2="90%" stroke="#ccc" id="line" />
  </g>
</svg>
2017年8月22日 23:49