Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

javascript - Detect click on text part of a block element

I have the following html element:

<h1>Some text</h1>

I need to detect a click and recognize whether it landed on the text part or the blank part of the element.

To preserve consistency of the rest of the app I cannot change the display of this element to inline or inline-block.

I also cannot modify the inner html of this element so splitting it into two <span> elements is not an option either.

The text inside this element is not constant and is in fact editable.

Can I detect a click only on the visible (text) part of this heading?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

QUESTION "I also cannot modify the inner html of this element so splitting it into two elements is not an option either." does this mean after the fact or before the fact? i.e is it that you cannot alter the HTML or that you can't go in and mutate the HTML via JS ?

Current Solution: I parse all elements with the .clickable identifier, remove & rebuild their text contents and place spans around them - this way i can add click listeners to the individual text/span elements - giving me access to the text itself.

const clickables = document.querySelectorAll('.clickable')
clickables.forEach(el => new Clickable(el))

function Clickable (el) {
  const _handleClick = ({target}) => console.log(target.innerHTML)
  const texts = el.textContent.split(/s/)
  
  el.innerHTML = ''
  
  texts.forEach(t => {
    const span = document.createElement('span')
    span.innerHTML = `${t} `
    span.addEventListener('click', _handleClick)
    el.appendChild(span)
  })
}
<h1 class="clickable">Some text</h1>

<h2 class="clickable">Some! more! text2</h1>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...