我需要一个脚本来在开关按钮打开时复制<img/>标签,并在开关按钮关闭时删除<img/>标签

时间:2014-08-19 06:34:12

标签: javascript jquery html css

我需要一个脚本来在开关按钮打开时复制<img>标签,并在开关按钮关闭时删除标签。我需要一个简单的方法。 这是开关按钮:

<div class="onoffswitch">
  <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
  <label class="onoffswitch-label" for="myonoffswitch">
    <span class="onoffswitch-inner"></span>
    <span class="onoffswitch-switch"></span>
  </label>
</div>

我试过了:

<script language="javascript">
        var changeImage = function(){
            img1="image/rez.jpg";
            switch(document.getElementById('myonoffswitch').src){
                case img1:
                    document.getElementById("myonoffswitch").src=img1;
                break;
                default:
                    document.getElementById("chango").src=img1;
                break;
            };
        };
    </script>

3 个答案:

答案 0 :(得分:2)

如果您只想显示/隐藏图片,可以使用下面的简单CSS。

<强> CSS

#myonoffswitch ~ img
{
 display:none;
}
#myonoffswitch:checked ~ img
{
 display:block;
}

<强> HTML

 <div class="onoffswitch">
   <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
    <label class="onoffswitch-label" for="myonoffswitch">
     <span class="onoffswitch-inner"></span>
     <span class="onoffswitch-switch"></span>
    </label>
   <img src="http://isc.stuorg.iastate.edu/wp-content/uploads/sample.jpg" />
 </div>

DEMO

答案 1 :(得分:0)

试试这个:

<强> DEMO

HTML:

 <div class="onoffswitch">
            <input id="Switch" type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch"/>
            <label class="onoffswitch-label" for="myonoffswitch">
                <span class="onoffswitch-inner"></span>
                <span class="onoffswitch-switch"></span>
            </label>
        </div>
         <img id="Sample" src="http://isc.stuorg.iastate.edu/wp-content/uploads/sample.jpg" />

        <div id="Div"></div>

SCRIPT:

 var variable;
        $("input[type=checkbox]").on("click", function () {
            $("#Div").text("");
            if ($('#Switch').is(':checked')) {
                variable = $("#Sample")[0].outerHTML;
                $("#Div").text(variable);
            } else {
                variable = "";
                $("#Div").text(variable);
            }

        });

答案 2 :(得分:0)

您只需更改图片来源,即可帮助您..

    if(im.src.match(""))
    {
    im.src="D:/Users/tobeused.jpg";
    }

    else
    {
    im.src="";
    }