如何使用querySelector单击svg ?



我正在尝试构建一个chrome扩展,使用下面的命令单击网页上的SVG,但它显示"点击"不是函数

谁能给我一些指导,以便解决这个问题?

document.querySelector("div[class^='SubmitChat__SubmitButton']").querySelector("svg > path(0)").click();
<form class="SubmitChat__SubmitChatWrapper-kLTVjd ezNulO">
<div id="PinToTop" style="display: none; border: groove; margin: 5px; padding: 5px;"></div>
<div class="DefaultComments__DefaultCommentsWrapper-drohEF dbvkCO">
<div class="SubmitChat__TextAreaWrapperBox-ijaLYA uQa-DJ">
<textarea data-track-category="Interaction_Comment" data-track-action="click" data-track-name="field_comment" class="SubmitChat__TextAreaWrapper-cEDMAF joGtiU" style="height: 44px;"></textarea>
</div>
<div class="SubmitChat__SubmitButton-kXYuum kSQpDq">
<span class="isvg loaded SubmitChat__SendMessageIcon-hzVurU lcJXRC">
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
<path d="M25.305 16.07L7.503 24.307a.802.802 0 01-1.111-.925l1.923-7.493h0L6.392 8.396a.8.8 0 011.111-.925l17.802 8.236a.2.2 0 010 .363zm-16.638-.181h16" fill="none" stroke="#28232D" stroke-linecap="round" stroke-width="1.5">
</path>
</svg>
</span>
</div>
</div>
</form>

你不能真正点击svg路径,但这里有一个解决方案:

const pathElem = document.querySelector("div[class^='SubmitChat__SubmitButton'] svg > path")
pathElem.onclick = () => console.log("clicked")
pathElem.dispatchEvent(new Event("click"))
pathElem.dispatchEvent(new Event("click"))
<form class="SubmitChat__SubmitChatWrapper-kLTVjd ezNulO">
<div id="PinToTop" style="display: none; border: groove; margin: 5px; padding: 5px;"></div>
<div class="DefaultComments__DefaultCommentsWrapper-drohEF dbvkCO">
<div class="SubmitChat__TextAreaWrapperBox-ijaLYA uQa-DJ">
<textarea data-track-category="Interaction_Comment" data-track-action="click" data-track-name="field_comment"  class="SubmitChat__TextAreaWrapper-cEDMAF joGtiU" style="height: 44px;"></textarea>
</div>
<div class="SubmitChat__SubmitButton-kXYuum kSQpDq">
<span class="isvg loaded SubmitChat__SendMessageIcon-hzVurU lcJXRC">
<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
<path d="M25.305 16.07L7.503 24.307a.802.802 0 01-1.111-.925l1.923-7.493h0L6.392 8.396a.8.8 0 011.111-.925l17.802 8.236a.2.2 0 010 .363zm-16.638-.181h16" fill="none" stroke="#28232D" stroke-linecap="round" stroke-width="1.5">
</path>
</svg>
</span>
</div>
</div>
</form>

请注意,.click()适用于HTML而不是SVG元素。MDN

还要注意,在您的例子中,单击事件处理程序可能不监听path元素,而是监听svgdivspan标记。

相关内容

  • 没有找到相关文章