如何动态给图片添加、隐藏按钮

  1. 图片的代码:

    <img id="img1" style="width: 100%;" src="../../../public/img/1.jpg" onmouseover="showButton(this,event);" onmouseout="hideButton(this,event)" />

 

  1. 按钮代码:

    <a id="a1" class="btn btn-primary" style="display: none;" href="#">Hello World</a>

     

  2. JavaScript代码:

    <script src="//cdn.bootcss.com/jquery/2.2.1/jquery.min.js "></script>

    <script src="//cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js "></script>

     

     

    <script type="text/javascript">

                function showButton(obj, e) {

                    var $obj = $(obj);

                    var X = $obj.offset().top;

                    var Y = $obj.offset().left;

                    

                    $('#a1').css({

                        'position': 'absolute',

                        'top': X + 10,

                        'left': Y + 10,

                        'z-index': '10',

                        'display': 'block'

                    });

                }

     

                function hideButton(obj, e) {

                    var $obj = $(obj);

                    if (e.pageX > $obj.offset().left && e.pageX < $obj.offset().left + $obj.width() && e.pageY > $obj.offset().top && e.pageY < $obj.offset().top + $obj.height()) {

                        //console.log('在范围内' + e.pageX + ' ' + e.pageY);

                    } else {

                        //console.log('在范围外' + e.pageX + ' ' + e.pageY);

                        $('#a1').hide();

                    }

                }

            </script>

     

  3. 效果如下

    当鼠标移到图片上呈现 按钮,移出时隐藏按钮。

    按钮使用Bootstrap样式

posted on 2016-04-12 15:14  my4piano  阅读(803)  评论(0编辑  收藏  举报

导航