gpt4 book ai didi

javascript - 如何使用 AngularJS 获取光标下的单词?

转载 作者:行者123 更新时间:2023-11-28 01:40:09 25 4
gpt4 key购买 nike

我需要在我的应用程序中使用 angularJS 获得此功能,以便每个单词在光标移动到它上方时显示吗?问题是该段落是由 ng-bind 动态生成的,我需要通过移动悬停来查看每个单词

<p>Each word will be wrapped in a span.</p>
<p ng-bind="myparagraph"></p>
Word: <span id="word"></span>

$('p').each(function() {
var $this = $(this);
$this.html($this.text().replace(/\b(\w+)\b/g, "<span>$1</span>"));
});
// bind to each span
$('p span').hover(
function() { $('#word').text($(this).css('background-color','#ffff66').text()); },
function() { $('#word').text(''); $(this).css('background-color',''); }
);

http://jsfiddle.net/5gyRx/

最佳答案

使用指令:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
$scope.model = {
word: "",
paragraph1: "Each word will be wrapped in a span.",
paragraph2: "A second paragraph here."
};
});


app.directive('wordUnderCursor', function() {
return {
scope: {
wordUnderCursor: "=",
wordUnderCursorContent: "="
},
link: function(scope, elment) {

scope.$watch('wordUnderCursorContent', function(newValue) {
console.log(newValue);
if (newValue) {
var $element = $(elment);

$element.html(newValue.replace(/\b(\w+)\b/g, "<span>$1</span>"));

$element.find('span').hover(
function() {
var $span = $(this);
$span.css('background-color', '#ffff66');
scope.$apply(function() {
scope.wordUnderCursor = $span.text();
});
},
function() {
var $span = $(this);
$span.css('background-color', '');
scope.$apply(function() {
scope.wordUnderCursor = "";
});
}
);
}
});
}
}
});

html:

   <body ng-controller="MainCtrl">
Paragraph 1:
<input type="text" ng-model="model.paragraph1"></input> <br />
Paragraph 2:
<input type="text" ng-model="model.paragraph2"></input>

<p word-under-cursor="model.word" word-under-cursor-content="model.paragraph1"></p>
<p word-under-cursor="model.word" word-under-cursor-content="model.paragraph2"></p>
Word: {{model.word}}
</body>

http://plnkr.co/edit/vRwCdXhtEFm7A4au1ago?p=preview

关于javascript - 如何使用 AngularJS 获取光标下的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26669472/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com