【发布时间】:2016-07-13 21:24:08
【问题描述】:
我希望在 span 元素中自动选择一些文本,以便用户轻松复制它。
我尝试过使用 .select() 但是,这似乎只适用于 <input> 和 <textarea> 元素;我的文本在<span> 内,我不想更改它,因为我使用另一个负责样式的组件处理我的应用程序中的所有文本(回答@dandavis,因为评论对我不起作用)。
我的文本在弹出窗口中呈现,因此我想为用户显示已选中。
这是我尝试过的:
import React from "react";
const PropTypes = React.PropTypes;
class CopyText extends React.Component {
constructor(props) {
super(props);
this.handleRef = this.handleRef.bind(this);
}
componentDidUpdate() {
this.copyText.select();
}
handleRef(component) {
this.copyText = component;
}
render() {
return (
<span ref={this.handleRef}>
{this.props.text}
</span>
);
}
}
CopyText.propTypes = {
text: PropTypes.string
};
export default CopyText;
谁能帮我为 span 元素创建一个自定义的自动选择文本功能? 非常感谢您的建议。
【问题讨论】:
-
你为什么不想使用
<input>?这样做很hacky会使其无法访问,并且在没有输入的情况下使其完全跨浏览器会很复杂。 -
使用 clipboard.js 并在 data-clipboard-text 属性中定义您的数据。 clipboardjs.com
-
如果您查看此答案stackoverflow.com/a/33547949/2085190,我相信您应该能够做类似的事情
-
@dandavis 我采纳了您的建议并使用了
<input>,因为我在使用@ktruong 方法支持所有浏览器时遇到了问题。谢谢你们。
标签: javascript html reactjs