Ой самое главное забыл дописать. Чтобы ваш вариант работал, нужно preventDefault выполнить по mousedown на #link.
<!DOCTYPE html>
<meta charset="utf-8">
<div>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<span id="test">test</span>
</div>
<script>
$Selection = {
standardsCompliant: typeof getSelection != "undefined",
get: function () {
return this.standardsCompliant ? getSelection() : document.selection;
},
getRange: function () {
return this.get()[this.standardsCompliant ? "getRangeAt" : "createRange"](0);
}
};
$Range = {
standardsCompliant: $Selection.standardsCompliant,
stringify: function (range) {
return this.standardsCompliant ? range.toString() : range.text;
}
};
//~~~~~~~~~~~~~~~~~~~~~~~
var text;
document.body.onmouseup = function () {
text = $Range.stringify($Selection.getRange());
};
var btn = document.getElementById("test");
btn.onmousedown = function (event) {
if (event && event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
};
btn.onclick = function () {
alert(text);
};
</script>
Сообщение от Cuprum
|
ЗЫ. $Selection - это объект, не так ли?
|
Да обычный объект.
Сообщение от Cuprum
|
А в чем преимущество вашего способа определения выделения (сложновато будет) перед функцией?
|
Ничего в этом коде сложного нет. Преимущество в том, что кросс-браузерная работа с Selection/Range/TextRange вынесена из тела функции и эти методы можно будет использовать где-то еще. В таком коде легче разобраться.
Короче не всегда лучше.