我想在用户点击Short Url锚点时突出显示工具提示中的文字,以便他可以复制粘贴它。工具提示由Twitter Bootstrap提供,标记如下所示:
<div class="shorturl">
<a href="#" rel="tooltip_r" data-original-title="http://tmblr.co/ZPPojuQzc9bb">Short URI</a>
</div>
我发现这个片段我认为会正常工作,除了我还没有弄清楚如何处理链接的点击(它们都不会滚动并突出显示工具提示中的文字)。
function selectText() {
if (document.selection) {
var range = document.body.createTextRange();
range.moveToElementText(document.getElementByClass('tooltip'));
range.select();
}
else if (window.getSelection) {
var range = document.createRange();
range.selectNode(document.getElementByClass('tooltip'));
window.getSelection().addRange(range);
}
}
我该如何使这项工作?输入非常感谢!
答案 0 :(得分:3)
我建议你这样做:Live demo (jsfiddle)
var selector = '[rel="tooltip_r"]'; // Links that will have the feature
var tooltipOptions = { // Some options for the tooltips (careful if you override the "defaults" set below)
placement: 'right'
};
var attribute = 'data-url'; // Attribute where to find the url, could be href
/* Be sure of what you are doing if you modify below this */
$elts = $(selector);
var defaultOptions = {
trigger: 'manual',
title: '<input type="text" readonly="readonly"/>'
};
var opts = $.extend({}, defaultOptions, tooltipOptions);
$elts.each(function() {
var $this = $(this);
var url = $this.attr(attribute);
$this.tooltip(opts);
$this.on('click.tooltip',function(e) {
$this.tooltip('show');
$this.data('tooltip').$tip.find('input').val(url).select()
.on('click', function(e){ e.stopPropagation(); });
e.preventDefault();
e.stopPropagation();
});
});
$('html').on('click.tooltip', function() {
$elts.tooltip('hide');
});
您可以使用某些样式来改进工具提示中的输入。例如:
.tooltip .tooltip-inner > input[type="text"] {
background: transparent;
border: none;
max-width: 100%;
width: auto;
padding: 0;
color: inherit;
}
如果在动态加载的内容中需要相同的功能,则需要使用delegated events。这是一个有效的jsfiddle。
var selector = '[rel="tooltip_r"]'; // Links that will have the feature
var tooltipOptions = { // Some options for the tooltips (careful if you override the "defaults" set below)
placement: 'right'
};
var attribute = 'data-url'; // Attribute where to find the url, could be href
var onClass = 'on'; // Class used to determine which tooltips are displayed
/* Be sure of what you are doing if you modify below this */
var defaultOptions = {
trigger: 'manual',
title: '<input type="text" readonly="readonly"/>'
};
var opts = $.extend({}, defaultOptions, tooltipOptions);
var selectorOn = selector+'.'+onClass;
$('body').on('click.tooltip', selector, function(e) {
var $this = $(this);
var url = $this.attr(attribute);
$this.data('tooltip') || $this.tooltip(opts);
$this.tooltip('show').addClass(onClass);
$this.data('tooltip').$tip.find('input').val(url).select()
.on('click', function(e){ e.stopPropagation(); });
e.preventDefault();
e.stopPropagation();
})
.on('click.tooltip', function() {
var $elts = $(selectorOn);
$elts.tooltip('hide');
});