我发现了很多使用各种形式的 onclick="this.select()"
选择元素的全部内容的解决方案。 ,但是是否可以使用 javascript 从元素中选择一行 onclick
?
例如,我正在编写一个 Linux 指南,其中涉及 <pre>
内的许多 bash 命令。和<code>
标签,并且我不希望用户必须单击并拖动来逐行选择每个命令行,因为这在几十行之后变得乏味。但是,我也不想将每个命令分离到它自己的可用于选择事件的元素中。
代码块示例:
<pre><code>
sudo apt-get install foo
cd /etc/bar
sudo cp baz.conf baz.local
sudo nano baz.local
</code></pre>
我希望用户只需单击一行即可选择它,但没有可供使用的类或 ID。我还希望这适用于任何 <pre><code>
页面上的 block ,而不仅仅是特定的一个。 jQuery 解决方案就可以了。
这可能吗?
最佳答案
您可以计算行数并将其与代码元素当前的垂直鼠标分隔线相乘(例如,如果您位于元素的中间,则为 0.5)。
这是相应的代码片段:
Math.floor(lines.length * (y/height))
基于这个想法的jQuery插件可以这样编码:
jQuery.fn.lineSelection = function(options) {
var _this = this,
height = null,
lines = this.text().split('\n'),
textChanged = false;
// remove first empty lines (optional)
while(lines[0] == '') {
textChanged = true;
lines.shift();
}
// remove last empty lines
while(lines[lines.length-1] == '') {
textChanged = true;
lines.pop();
}
if(textChanged) {
this.text(lines.join('\n'));
}
height = this.height();
this.on('click', function() {
var y = event.offsetY,
// now use the described formula
lineIndex = Math.floor(lines.length * y/height),
line = lines[lineIndex];
_this.trigger('lineClicked', [line, lineIndex]);
});
if(options.lineClicked) {
this.on('lineClicked', options.lineClicked);
}
};
该插件可以这样使用:
$('pre > code').lineSelection({
lineClicked: function(event, text, index) {
console.log(text, index);
}
});
另请查看工作 jsfiddle-demo
关于javascript - 使用 javascript 选择元素内的单行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25896751/