我有一个容器,里面有孩子。其中一个孩子中有text
个。另一个人中有img
。
问题是,当用户选择text
(使用鼠标,就像选择word doc中的文本等)时,假设用户点击图像源(占据了父图像),{ {1}}不清楚。
文字保持text
我点击selection
来源。如何解决这个问题。
我要求,即使用户点击img
,也需要清除选择。
img
$('.container').on('click', function (e) {
var target = $(e.target);
//window.getSelection().empty(); i can't use this.
console.log(target); //getting img.
});
.container{
border:1px solid green;
width:300px;
height:150px;
position:relative;
}
.imageHolder{
position:absolute;
left:0;
top:0;
}
.textHolder {
position:absolute;
}
任何人都可以帮我解决这个问题吗?可能如果<div class="container">
<div class="imageHolder"><img src="http://thumb7.shutterstock.com/display_pic_with_logo/599431/127612211/stock-photo-green-apple-isolated-on-white-background-127612211.jpg" width=300 height=150></div>
<div class="textHolder">some text goes here</div>
</div>
或js
中有解决方案,我希望避免使用css
功能。
如果我使用此html
功能,我根本无法选择js
..
text
答案 0 :(得分:2)
尝试以下操作。
$('.container').on('click', function (e) {
var target = $(e.target);
//window.getSelection().empty(); i can't use this.
//console.log(target); //getting img.
var txt=$(this).find(".textHolder");
if(target[0].tagName === 'IMG')
{
txt.addClass('noselect');
txt.attr('unselectable','on');
}else{
txt.removeClass('noselect');
txt.attr('unselectable','off');
}
});
$('.container .textHolder').on('mousedown',function(){
$(this).removeClass('noselect');
$(this).attr('unselectable','off');
});
.container{
border:1px solid green;
width:300px;
height:150px;
position:relative;
}
.imageHolder{
position:absolute;
left:0;
top:0;
}
.textHolder {
position:absolute;
}
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="imageHolder"><img src="http://thumb7.shutterstock.com/display_pic_with_logo/599431/127612211/stock-photo-green-apple-isolated-on-white-background-127612211.jpg" width=300 height=150></div>
<div class="textHolder">some text goes here</div>
</div>
答案 1 :(得分:0)
也许这很愚蠢,但我不明白为什么你不能在.imageHolder
上附上这个事件?
$('.imageHolder').on('click', function(e) {
if (window.getSelection.empty) { // Chrome
window.getSelection().empty();
}
else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
else if (document.selection) { // IE?
document.selection.empty();
}
});
.container {
border: 1px solid green;
width: 300px;
height: 150px;
position: relative;
}
.imageHolder {
position: absolute;
left: 0;
top: 0;
}
.textHolder {
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="imageHolder">
<img src="http://thumb7.shutterstock.com/display_pic_with_logo/599431/127612211/stock-photo-green-apple-isolated-on-white-background-127612211.jpg" width=300 height=150>
</div>
<div class="textHolder">some text goes here</div>
</div>