如何在javascript中制作复制文本按钮

时间:2014-12-13 15:05:57

标签: javascript jquery html css

我创建了一个不同的右键单击上下文菜单,并希望包含一个“复制文本”按钮,但我不知道要使用哪种类型的代码。我已经尝试了CopyText(this.form.txtSelect);但是没有把它放在正确的/它不兼容,而且我怎么会删除子弹,我尝试将其更改为类似<a>但它不使用css样式
这是我目前的脚本: JSfiddle

HTML:

TEST Text
<ul class='custom-menu'>
  <li data-action = "first">Copy Text</li>
  <li data-action = "second">Second thing</li>
  <li data-action = "third">Third thing</li>
</ul>

使用Javascript:

function CopyText(el){
    var selectedText = "";
    if(window.getSelection){
        selectedText = window.getSelection();
    }else if (document.getSelection){
        selectedText = document.getSelection();
    }else if (document.selection){
        selectedText = document.selection.createRange().text;
    }
    if(selectedText != ""){
        selectedText = selectedText.toString();
        el.focus();
        el.value = selectedText;
        }else {
        alert("Select a text in the page and then press this button!");
    }
}
// Trigger action when the contexmenu is about to be shown
$(document).bind("contextmenu", function (event) {

    // Avoid the real one
    event.preventDefault();

    // Show contextmenu
    $(".custom-menu").finish().toggle(100).

    // In the right position (the mouse)
    css({
        top: event.pageY + "px",
        left: event.pageX + "px"
    });
});


// If the document is clicked somewhere
$(document).bind("mousedown", function (e) {

    // If the clicked element is not the menu
    if (!$(e.target).parents(".custom-menu").length > 0) {

        // Hide it
        $(".custom-menu").hide(100);
    }
});


// If the menu element is clicked
$(".custom-menu li").click(function(){

    // This is the triggered action name
    switch($(this).attr("data-action")) {

        // A case for each action. Your actions here
        case "first": CopyText(this.form.txtSelect); break;
        case "second": alert("second"); break;
        case "third": alert("third"); break;
    }

    // Hide it AFTER the action was triggered
    $(".custom-menu").hide(100);
  });

CSS:

.custom-menu {
    display: none;
    z-index: 1000;
    position: absolute;
    overflow: hidden;
    border: none;
    white-space: nowrap;
    font-family: sans-serif;
    font-size: 12px;
    background: #FAFCFD;
    color: #6E6E6E;
    border-radius: 0px;
}

.custom-menu li {
    padding: 8px 6px;
    cursor: pointer;
}

.custom-menu li:hover {
    background-color: #49C1FF;
    color: #FFFFFF;
}

0 个答案:

没有答案