Add soft hyphens in a CMS: getting it to work in Chrome

删除回忆录丶 提交于 2020-01-06 14:15:26

问题


­ is awesome, especially because it works in all popular browsers. You put it in the middle of a word, which tells the browser that the word may be broken in that place. If it does get broken there, a hyphen appears. If it doesn't, the character remains invisible.

But it's not very easy to use for content authors: you have to go into the HTML to add it. Even if you can add it in a CMS, you can't see where it is as soon as you inserted it.

So I went ahead and declared an inline style in my CMS for my authors to use. They can select part of a word, for example <span class="shy">communi</span>cation, and then a css rule will magically add the &shy; using an :after pseudo-element! And with some CMS-specific CSS I can give that tag a dotted underline to show that it's got one of those soft hyphens. Works in Firefox and IE8+. Neat.

But the hyphen doesn't appear in Google Chrome! It breaks the word, but there's no dash. I knew it didn't support the hyphens css property, but it does normally support &shy;.

But all right, so I removed the css style and wrote some javascript to add ­ upon load. Using jQuery, I tried both .append and .after. I even tried innerHTML += '&shy;'. None of them work! How disappointing...

How to work around this?


回答1:


I figured out a solution while writing this question.

&shy; seems to work in Chrome only if there is another character right after it (and before it). The issue above is that the &shy; character is always the last one within the tag. So I added a space and then closed that space with css. Unfortunately this does not work with a css pseudo element, so I still needed javascript.

I did need to use browser detection because adding the space made it stop working in Internet Explorer and Firefox. (using &nbsp; makes it work in Firefox, but not IE)

$(".shy").each(function(){
    this.innerHTML += '&shy; '; // add the soft hyphen (for all browsers)

    // Only Chrome has an issue
    if(/chrom(e|ium)/.test(navigator.userAgent.toLowerCase())) {
        this.innerHTML += ' '; // add a space
        $(this).css('margin-right', '-.26em'); // close the gap from the space
    }
});

To be used like this:

<span class="shy">communi</span>cation


来源:https://stackoverflow.com/questions/27976771/add-soft-hyphens-in-a-cms-getting-it-to-work-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!