简体   繁体   English

如何设置文本修饰:仅针对特定内容加下划线

[英]How to set text-decoration: underline only for specific content

I have a input tag and where I am getting input value like this. 我有一个输入标签,我得到这样的输入值。

input.value += " " + value + ";" ;

In my css I have text-decoration: underline; 在我的CSS中我有text-decoration: underline; but here underline is coming in "space" and ";" 但这里的下划线是“空间”和“;” both the place. 这两个地方。 Is there any way I can decorate only text part. 有什么方法我可以只装饰文字部分。

My Code is like : 我的代码就像:

var div = document.getElementById(divID);

var myTable = '<input type="text" id="myInput"  list="myUL" onclick = "openingList()" onkeyup="openingList()" style="width:30%;" >' +
    '<div id="triggers">' + '<img class="trigger" onclick ="deleteValue()" src="css/clearT.png" id="cross" />' + '<img class="trigger" src="css/combo_arrow.png" onclick = "openingList()" id="arrow" />' + '</div>' +
    '<ul id="myUL" hidden=true>' + '<li>' + '<a href="#" ></a>' + '</li>' + '</ul>';

div.innerHTML = myTable;

function selectItem(input, value) {
    var newinput = input.value.split(';');
    newinput[newinput.length - 1] = "";
    input.value = newinput.join(";");
    input.value += " " + value + ";" + "";    
}

Current it is coming like this. 目前它是这样的。

我得到了什么

What exactly I want here 我究竟想要什么

我想要的是

try this concept: https://jsfiddle.net/uza1pbnw/ 尝试这个概念: https //jsfiddle.net/uza1pbnw/

Example - 1 with Pure JS 示例 - 使用Pure JS的1

var text = "How are you doing today?";
text = text.split(" ");
    len = text.length,
    result = []; 

for( var i = 0; i < len; i++ ) {
    result[i] = '<span>' + text[i] + '</span>';     
}   

console.log(result.join(' '));

Example - 2 with JQuery 示例 - 使用JQuery的2

HTML HTML

<p>hello world text done</p>

CSS CSS

<style>
    p span {
        text-decoration: underline;
    }

</style>

JS JS

<script>
    $('p').each(function() {
        var text = $(this).html().split(' '),
            len = text.length,
            result = [];

        for (var i = 0; i < len; i++) {
            result[i] = '<span>' + text[i] + '</span>';
        }
        $(this).html(result.join(' '));
    });

</script>

https://jsfiddle.net/princesodhi/0h8oqknz/4/ https://jsfiddle.net/princesodhi/0h8oqknz/4/

You could write a javascript function that you pass a word to, and it returns that word wrapped in a <span> with text decoration on it. 你可以写一个你传递一个单词的javascript函数,它会返回包含在带有文本修饰的<span>中的单词。

var myFullString = tdu(input.value) += " " + tdu(value + ";") ;


function tdu(str) { //Text decoration underline function
    return "<span style='text-decoration: underline'>" + str + "<span>"
}

As other answers suggest, you would need to wrap specific portions of the text in an element (such as a span) in order to apply styles to those targeted text segments. 正如其他答案所示,您需要将文本的特定部分包装在元素(例如跨度)中,以便将样式应用于这些目标文本段。

Because we can't insert rendered HTML inside an input field, I think the best approach would be to use an additional element to display styled text. 因为我们无法在输入字段中插入呈现的HTML,所以我认为最好的方法是使用其他元素来显示样式文本。 Responding to key events, you would then use a regex to search the value for text that should/shouldn't be styled (underlined). 响应键事件,然后使用正则表达式搜索应该/不应该设置样式的文本的值(带下划线)。

Personally, I am against creating custom fields that try to recreate or supplement browser behavior. 就个人而言,我反对创建尝试重新创建或补充浏览器行为的自定义字段。 With that in mind, I like the idea of using the extra element to simply control the underline appearance and not mess with the actual input's text or value. 考虑到这一点,我喜欢使用额外元素来简单地控制下划线外观而不是弄乱实际输入的文本或值。

Here's an example fiddle. 这是一个小例子。

What's happening in the fiddle: 小提琴里发生了什么:

  • The input field is displayed normally. 输入字段正常显示。 Let's just let it do it's thing. 让我们让它做到这一点。
  • The input element ('x-field-input') and the text display element ('x-field-text') have identical font and box model properties so that they align dimensionally. 输入元素('x-field-input')和文本显示元素('x-field-text')具有相同的字体和框模型属性,因此它们在尺寸上对齐。
  • The additional element 'x-field-text' has transparent text so that the text within it is not visible. 附加元素“x-field-text”具有透明文本,因此其中的文本不可见。 However, instead of 'underline' it uses a bottom border to create the desired appearance. 但是,它不使用“下划线”,而是使用底部边框来创建所需的外观。 I like the use of border-bottom here because you have control of the color if needed. 我喜欢在这里使用border-bottom,因为如果需要你可以控制颜色。
  • A trivial regex pattern looks for instances of " : " (optional spaces). 一个简单的正则表达式模式查找“:”(可选空格)的实例。
  • The regex matches are then inserted as innerHTML of the 'x-field-text' element. 然后将正则表达式匹配作为'x-field-text'元素的innerHTML插入。 If the string segment does not match " : ", it is wrapped in a span. 如果字符串段与“:”不匹配,则将其包含在span中。

Your formatting is very specific and since I'm not aware of other formats or string conditions that you might want to capture I only included the specific example of " : ". 您的格式非常具体,因为我不知道您可能想要捕获的其他格式或字符串条件,我只包括“:”的具体示例。 You could adapt this code to accomplish other formats. 您可以调整此代码以完成其他格式。

Also, I threw this together quickly so only refer to this code as an example. 另外,我快速将它们放在一起,所以仅以此代码为例。 It could most certainly be improved. 它当然可以得到改善。

 (function() { let CustomField = function(el) { this.init = () => { this.el = el; this.inputEl = this.el.querySelector('.x-field-input'); this.textEl = this.el.querySelector('.x-field-text'); this.renderText(); this.bindUserEvents(); }; this.bindUserEvents = () => { this.inputEl.addEventListener('keyup', this.inputKeyUp.bind(this)); }; this.inputKeyUp = () => { this.renderText(); } this.renderText = function() { let regex = new RegExp(/(.*)((?:\\W)?\\:(?:\\W)?)(.*)/, 'g'); let value = this.inputEl.value; let groups = regex.exec(value); let html = ''; if (groups && groups.length) { for(var i = 1; i < groups.length; i++) { if (/((?:\\W)?\\:(?:\\W)?)/.test(groups[i])) { html += groups[i]; } else { html += '<span>' + groups[i] + '</span>'; } } } this.textEl.innerHTML = html; } return this; }; let customFieldEls = document.querySelectorAll('.x-field'); customFieldEls.forEach((n) => { let customField = new CustomField(n); customField.init(); }); }()); 
 .x-field { position: relative; display: block; width: 100%; } .x-field .x-field-input, .x-field .x-field-text { position: absolute; top: 0; left: 0; box-sizing: border-box; display: block; width: 100%; height: 50px; padding: 10px; font-size: 15px; font-family: Arial, Helvetica, sans-serif; line-height: 30px; vertical-align: middle; } .x-field .x-field-text { pointer-events: none; color: transparent; background: transparent; border: 1px solid gray; } .x-field .x-field-text span { border-bottom: 1px solid gray; } 
 <div class="x-field"> <input class="x-field-input" type="text" value="United States : Afghanistan" /> <div class="x-field-text"></div> </div> 

After many try i found one way to do this. 经过多次尝试,我找到了一种方法来做到这一点。

Using div contenteditable="true" property you skip underline from specific characters. 使用div contenteditable="true"属性可以跳过特定字符的下划线。

Hope this will help for displaying as per requirements. 希望这有助于按要求显示。

I create span for set underline from input value and set it to editable div. 我从输入值创建设置下划线的范围并将其设置为可编辑的div。

 String.prototype.replaceAll = function(search, replacement) { var target = this; return target.replace(new RegExp(search, 'g'), replacement); }; function funUnderLine(){ // DIV value. var underLine = document.getElementById('likeInput'); // Get hidden input for post. var actualValue = document.getElementById('actualValue'); // Create newStr variable for set temporary value. var newStr = ""; // Split space and UD variables. var splitVal = actualValue.value.split(""); var tempArray = ['_words_']; var word = []; var str = ""; // Set spllited value to an array. for(val in splitVal){ if(splitVal[val]==' '){ var temp = []; temp['_space_'] = splitVal[val]; tempArray.push(temp); } else if(splitVal[val]==';'){ var temp = []; temp['_semicolon_'] = splitVal[val]; tempArray.push(temp); } else{ tempArray.push(splitVal[val]); } } // Generate underlined strings except [space] and [semicolon]. for(val in tempArray){ if( Object.prototype.toString.call(tempArray[val]) === '[object Array]' ) { if( Object.prototype.toString.call(word) === '[object Array]' ) { str += '<span style="text-decoration: underline;">'; for(v1 in word){ str += word[v1]; } str += '</span>'; } for(v in tempArray[val]){ str += tempArray[val][v]; } var word = []; } else{ if(tempArray[val] != '_words_'){ word.push(tempArray[val]); } } } // Check only words. if(word.length>0){ str += '<span style="text-decoration: underline;">'; for(val in word){ str += word[val]; } str += '</span>'; } // Append new html. underLine.innerHTML = ""; // First blank old html. underLine.innerHTML = str; // Than append new html. } funUnderLine(); // Load first time. 
 #likeInput { -webkit-appearance: textfield; background-color: white; -webkit-rtl-ordering: logical; user-select: text; cursor: auto; padding: 1px; border-width: 2px; border-style: inset; border-color: initial; border-image: initial; text-rendering: auto; color: initial; letter-spacing: normal; word-spacing: normal; text-transform: none; text-indent: 0px; text-shadow: none; display: inline-block; text-align: start; margin: 0em; font: 13.3333px Arial; border: 1px solid #a9a9a9; -webkit-writing-mode: horizontal-tb; } 
 <input type="text" id="actualValue" value="United State ; India;" onkeyup="funUnderLine();"/> <label>Text Box</label> <br /><br /> <div contenteditable="true" id="likeInput"></div> <label>Editable Div</label> 

Many complex and great answers. 许多复杂而精彩的答案。 If you want it done fast and simple: 如果你想快速简单地完成它:

input.value += " " + value + ";" ;

Changes to: 变更为:

CSS: CSS:

.ul {text-decoration: underline;}

JS: JS:

startUL = "<span class='ul'>";
endUL = "</span>";
startUL + input.value + endUL += " " + startUL + value + endUL + ";" ;

And call it a day. 并称它为一天。 Then, once this is working nicely for you, revisit the requirements for the display to determine a better display requirement since underlining is sketchy UX when it's not: a) a hyperlink or b) indicative of something important to the user. 然后,一旦这对你有效,重新审视显示的要求,以确定更好的显示要求,因为下划线是粗略的用户体验,当它不是:a)超链接或b)指示对用户重要的事情。

Happy coding. 快乐的编码。

You could use text-decoration-skip 你可以使用text-decoration-skip

text-decoration-skip: spaces

It is not being supported by all major browsers though. 但它并没有得到所有主流浏览器的支持。

just adjust the current strings in input.value on this line : 只需在此行调整input.value的当前字符串:

input.value += " " + value + ";" ;

To something like this line : 对于像这样的行:

input.value += ' ' + '<p class="Foo">'  + value + ';</p>' ;

Next you can now add a CSS selector Foo with text-decoration: underline 接下来,您可以添加带有text-decoration: underline的CSS选择器Foo text-decoration: underline

OR replace class="Foo" with style="text-decoration: underline" 或者style="text-decoration: underline"替换class="Foo" style="text-decoration: underline"

You could use <span> , <p> , <h5> tags or any HTML typography tags. 您可以使用<span><p><h5>标记或任何HTML排版标记。

Try giving span to such items and specify id to it and give following styling to that id 尝试为这些项目提供span并为其指定id并为该id提供以下样式

text-decoration :none;

Hope it helps 希望能帮助到你

Okay after having a thorough look at the problem, I have actually realized that there is not any simple solution. 好的,仔细看看问题后,我实际上已经意识到没有任何简单的解决方案。 As styles can apply to the entirety of an element only, a solution will require at least one element per required style. 由于样式只能应用于整个元素,因此每个所需样式的解决方案至少需要一个元素。

Solution

You cannot achieve this with a single input element. 使用单个输入元素无法实现此目的。 Also, JavaScript is required for a solution. 此外,解决方案还需要JavaScript。 So, there are three sections of the input: 因此,输入有三个部分:

  • that before the point at which changes are being applied 在应用更改之前的那个

  • that after the point at which changes are being applied 在应用更改之后

  • that at the point the changes are being applied 在应用更改时

You should initially include a regular input element and forgo any of the required styling. 您应该首先包含常规输入元素并放弃任何所需的样式。 Use JavaScript to replace the input with a suitable container element. 使用JavaScript将输入替换为合适的容器元素。 This can be styled to mimic an input element. 这可以设计为模仿输入元素。

As you add values, use JavaScript to identify the above-mentioned three divisions. 在添加值时,使用JavaScript来标识上述三个部分。 Wrap them in suitable elements (spans would be ideal) and style as needed. 根据需要将它们包裹在合适的元素中(跨度是理想的)和样式。

Consider the following starting point: 考虑以下起点:

<div class="input">
  <span class="before"> </span>
  <span class="edited">value</span>
  <span class="after">;</span>
</div>

This will serve as a proper solution to the mentioned problem and also for similar future problems that you encounter. 这将成为上述问题的正确解决方案,也是您遇到的类似未来问题的解决方案。

PURE CSS PURE CSS

For example: 例如:

text-decoration-skip: none;
text-decoration-skip: objects;
text-decoration-skip: spaces;
// etc ...

Full documentation here: MDN - text-decoration-skip 这里有完整的文档: MDN - text-decoration-skip

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM