我正在做一个分两栏的网站,左边是你可以写的,右边是用特殊设计显示的。
问题是,我想在右侧允许换行,但它不显示。我怎么能那样做?
这是我的设计预览。要查看完整图片,这里是 > Fiddle HERE
function wordsinblocks(self) {
var demo = document.getElementById("demo"),
initialText = demo.textContent,
wordTags = initialText.split(" ").map(function(word) {
return '<span class="word">' + word + '</span>';
});
demo.innerHTML = wordTags.join('');
self.disabled = true;
fitWords();
window.addEventListener('resize', fitWords);
}
$(function() {
$('textarea.source').livePreview({
previewElement: $('p#demo'),
allowedTags: ['p', 'strong', 'br', 'em', 'strike'],
interval: 20
});
});
window.onload = wordsinblocks(self);
function fitWords() {
var demo = document.getElementById("demo"),
width = demo.offsetWidth,
sizes = [7.69230769230769, 23.07692307692307, 46.15384615384614, 100],
calculated = sizes.map(function(size) {
return width * size / 100
}),
node,
i,
nodeWidth,
match,
index;
for (i = 0; i < demo.childNodes.length; i++) {
node = demo.childNodes[i];
node.classList.remove('size-1', 'size-2', 'size-3', 'size-4');
nodeWidth = node.clientWidth;
match = calculated.filter(function(grid) {
return grid >= nodeWidth;
})[0];
index = calculated.indexOf(match);
node.classList.add('size-' + (index + 1));
}
}
最佳答案
只要按下 Enter
键,您就可以插入换行符。一种方法是使用 .which
或 .keyCode
:
$(document).keydown(function(e){
var event = e.which || e.keyCode;
if (event == 13){
//do something like this
return '<span class="word"><br/>' + word + '</span>';
}
});
“13”是Enter
的字符代码。我已经在您的代码中对其进行了测试,并且运行良好。您只需将其放置(也对其进行更改)不会影响您的任何功能代码的位置。
第二种方法是在执行某些操作之前准确复制“写入”面板中的内容,例如通过将单词封装在不同的突出显示中来分隔单词等。
[更新#1]
只是一段用于测试的代码。
function wordsinblocks(self) {
var demo = document.getElementById("demo"),
initialText = demo.textContent,
wordTags = initialText.split(" ").map(function(word) {
return '<span class="word">' + word + '</span>';
});
$(document).keydown(function(e){
var event = e.which || e.keyCode;
if (event == 13){
demo.innerHTML = wordTags.join(' <br/> ');
} else{
demo.innerHTML = wordTags.join('');
}
});
self.disabled = true;
fitWords();
window.addEventListener('resize', fitWords);
}
[更新#2]
function wordsinblocks(self) {
var demo = document.getElementById("demo"),
initialText = demo.innerText.replace(/\n\r?/g,"<br/>"),
wordTags = initialText.split(" ").map(function(word) {
return '<span class="word">' + word + '</span>';
});
demo.innerHTML = wordTags.join('');
self.disabled = true;
fitWords();
window.addEventListener('resize', fitWords);
}
关于javascript - 允许使用 javascript + LivePreview 换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37418348/