如果对象离窗口的边界太近,是否可以移动HTML对象?

时间:2019-05-08 16:00:43

标签: javascript html css

上下文::当我将鼠标悬停在标签图像上时,会出现一个框,其中显示了艺术品信息。我的问题是,如果标签离窗口的左边界或右边界太近,则会剪切该框,而我们将无法再看到这些信息。

实际问题: 如果CSS或JavaScript太大,无法容纳在屏幕中,是否可以将其移动到右侧?

https://imgur.com/a/tO5JnZq

该图显示了被剪切的框,因为它太靠近窗口的左边框

2 个答案:

答案 0 :(得分:1)

我最近在jquery中做了类似的事情,基本上,当触发工具提示时,您会得到屏幕宽度和光标的屏幕位置,如果不合适,则将其移至直到:

$('.showtooltip').on('click touchend', function (e){
    const screenWidth = $(window).width() / 2;
    const x = e.pageX; //Cursor X position
    const y = e.pageY; //Cursor Y position
    const tooltipDirection = e.pageX < screenWidth ? 10 : -200;// if click is on the right of the screen show tooltip to the left of event(-200px)
    const content = "Here's a tooltip";

    if (content.length > 0)
    {
        //insert a span with your content or whatever here
        $('body').append("<div class='custom-tooltip' style='position:absolute;left:" + (x + tooltipDirection) + "px;top:" + y +"px;background-color:#ffa;border:1px solid #cc9;padding:3px;font-size:13px;-moz-box-shadow: 2px 2px 11px #666;-webkit-box-shadow: 2px 2px 11px #666;'>" + content + "</div>");


         setTimeout(function(){//remove the span after 3 seconds
             $('.custom-tooltip').fadeOut(function(){
                 $(this).remove();
             });
         },3000);
    }   
});

答案 1 :(得分:-2)

使用嵌入式CSS,在左边留出空白或边距:

style="margin:10px" or "padding:10px"

右侧的边距或填充:

style="position:absolute,right:10px,margin:10px" or "padding:10px"

希望它能满足您的需求。