使用DIV作为按钮时保持文本选择 [英] Maintain Text Selection When Using DIV as a button

查看:64
本文介绍了使用DIV作为按钮时保持文本选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这是与浏览器相关的问题?我现在在Chrome上...

Maybe this is a browser related issue? I'm on Chrome at the moment...

我想要完成的是允许用户保存他们选择(突出显示)的文本带光标的页面。

What I'm trying to accomplish is allow the user to save text that they've selected (highlighted) on the page with their cursor.

我有javascript / jQuery / ajax所有设置...当我通过控制台测试它时它就像一个魅力。

I've got the javascript/jQuery/ajax all setup...and it works like a charm when I'm testing it via the console.

ie - 我选择了一些文本,然后运行此命令。

i.e. - I select some text and then run this command.

alert(getSelected());

我将获得包含所选字符的警报弹出窗口。
...所以它在理论上有效。

To which I get an alert popup with the selected characters. ...so it works in theory.

但是 - 当我想使用按钮拨打电话时,发生的事情是文本选择消失了首先,因此我无法看到/保存他们所选择的内容。

HOWEVER - When I want to use a button to make the call, what's happening is that the text selection dissapears FIRST, and thus I am unable to then see/save what they've selected.

<script>
$('#save').click(function(){
  var selected_text = getSelected();
});
</script>

<div id="save"><img src="the_save_button.jpg" height="50" width="50" /></div>

点击保存DIV后,是否有办法维护文本选择?

Is there a way to maintain the text selection upon clicking/after clicking the "save" DIV?

对任何和所有解决方案开放!!谢谢!

Open to any and all solutions!! Thanks!

推荐答案

一个简单的选择是使用 mousedown 而不是点击。但是,这与按钮的本机行为不同,即在释放鼠标按钮时触发动作,因此UI不是很好。

One easy option is to use mousedown instead of click. However, this is different to the native behaviour of buttons, which is to fire an action when the mouse button is released, so is not great UI.

另一种选择是使用专有CSS属性和IE和Opera的 unselectable 属性的组合使可点击元素无法选择,这可以防止点击清除选择:

Another option is to make the clickable element unselectable, using a combination of proprietary CSS properties and the unselectable attribute for IE and Opera, which prevents the click from clearing the selection:

演示: http://jsfiddle.net/timdown/UUQJs/

CSS:

.unselectable {
    -khtml-user-select: none;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
}

HTML:

<div id="save" unselectable="on" class="unselectable"><img
   src="the_save_button.jpg" height="50" width="50" unselectable="on" /></div>

这篇关于使用DIV作为按钮时保持文本选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆