The value
attribute within an input
element can be accessed using JavaScript with HTMLElement.value
. Unfortunately, styles will apply to the whole input value. So this is a bit tricky.
Since the value
is a single string, which will contain two words. I used some JavaScript to split the string into array of words so then you can strike-through the first word using CSS with text-decoration: line-through
and the second word can have text-decoration: none
(no strike-through).
I wouldn't recommend this in a production environment, but I made it work by creating two span
elements to hold the two words and styled them accordingly. I then gave the original input
value a transparent text color with color: transparent
and positioned the two span
elements on top of the input value to achieve your desired first word strike-through second word without.
const textBlot = document.querySelector(".text-blot");
const demo = document.querySelector(".demo");
const word1 = document.createElement("span");
const word2 = document.createElement("span");
word1.setAttribute("class", "strike");
word2.setAttribute("class", "no-strike");
demo.appendChild(word1);
demo.appendChild(word2);
const arr = textBlot.value.split(" "); // create an array of words
word1.innerHTML = arr[0];
word2.innerHTML = " " + arr[1];
.text-blot {
/* text-decoration: line-through; */
z-index: 1;
color: transparent;
}
.strike {
text-decoration: line-through;
}
.no-strike {
text-decoration: none;
}
.demo span {
position: relative;
left: -9.5rem;
z-index: 99;
}
<div class="demo">
<input type='text' value='two words' class='text-blot'>
</div>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…