Copy selected item's text from select control html

后端 未结 4 1254
说谎
说谎 2021-01-17 05:11

I have a select control with pre defined values and I want my users to be able to copy the selected item\'s text with CTRL + C

I don\'t want them to be able to chang

4条回答
  •  既然无缘
    2021-01-17 05:34

    Here's a way to mimick the behaviour you are after, with a bit of positioning magic and jQuery. The code is only tested on Chrome, so it might need a bit of tweaking to look good in all browsers. Also see the note at the bottom of the page for IE7

    http://jsfiddle.net/FvFVJ/

    The html is rather simple. Just add an input field next to your select and wrap both in a div. You can add the property readonly to the input field, to disable editing if you wish


    .wrap {
        position: relative;
        border: 1px solid #ccc;
        height: 21px;
        border-radius: 4px;
    }
    
    .wrap select {
        opacity: 0;
        position: absolute;
        top: -3px;
        left: -3px;
        z-index: 1;
    }
    
    .wrap input {
        display: inline-block;
        position: absolute;
        top: 0;
        left: 2px;
        z-index: 2;
        border: 0;
    }
    
    .wrap:after{
        content: "\25BE";
        font-size: 1.5em;
        position: absolute;
        right: 0;
        top: -3px;
        z-index: 0;
    }
    

    Both elements are position:absolute inside the wrapper. Things to notice

    1. The select element has opacity:0 which makes it invisible but still clickable
    2. The pseudo element .wrap:after, which acts as a dropdown arrow (*)
    3. The z-index ordering, which puts the input on top of the select, expect of the corner which will act as the dropdown button
    4. The widths need to be properly fixed, either in css (static) or by javascript (dynamic)

    $(function () {
        $(".wrap").width($(".wrap select").width());
        $(".wrap input").width($(".wrap select").width() - 20);
        $(".wrap select").on("change", function () {
            var txt = $(this).find(':checked').text();
            $(".wrap input").val(txt);
        });
    });
    

    And finally some javascript to set the correct widths for our elements and update the input text everytime we choose a new value from the select.


    (*) : The pseudo element will not work in IE7 or . A workaround is to use a background image for the .wrap element

提交回复
热议问题