【问题标题】:Insert a toolbar div to a page and push the body down将工具栏 div 插入页面并将正文向下推
【发布时间】:2015-10-05 11:20:05
【问题描述】:

我想在单击按钮时将工具栏注入正文。它应该固定在顶部,即使用户向下滚动也应该保留在那里。我在向下移动正文时遇到了一些问题,因为工具栏覆盖了一些正文内容并在顶部留下了空白区域。这是我的代码

HTML

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
  <div>
    <p>Hello</p>
    <button onclick="inject()">Inject</button>
  </div>
</body>
</html>

CSS

#customToolbar1234 {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100% !important; 
    height: 35px;
    border: 0 !important;
    background: #e3e3e3 !important;
    z-index: 9999999 !important;
}

JS

function inject() {

    var sg_div = $('<div>').attr('id', 'customToolbar1234').addClass('selectorgadget_bottom').addClass('selectorgadget_ignore');
    $('body').append(sg_div);

    var first_button = $('<input type="button" value="0"/>');
    sg_div.append(first_button);


    $('body').css({
        'transform': 'translateY(35px)',
        'transition': 'transform 0.4s ease'
    });
}

在 JS 代码中,如果我将 div 附加到 html 标签而不是 body,那么代码可以正常工作,但我不想在 body 标签之外添加 div。我也不想使用 iframe,只是一个 div。我该怎么做?这是JSbin 链接。

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    在这里,修复了代码。您使用 javascript 在 body 标记上应用了错误的 CSS。更改仅适用于 Javascript

    function inject() {
    
    	//var url = chrome.extension.getURL('toolbar.html');
    
        var sg_div = $('<div>').attr('id', 'customToolbar1234').addClass('selectorgadget_bottom').addClass('selectorgadget_ignore');
        $('body').append(sg_div);
    
        var first_button = $('<input type="button" value="0"/>');
        sg_div.append(first_button);
    
    
    	$('body').css({
        	'padding-top':'35px',
        	'transition': 'transform 0.4s ease'
    	});
    
    
     
    }
    #customToolbar1234 {
        position: fixed !important;
        top: 0 !important;
        left: 0 !important;
        width: 100% !important; 
        height: 35px;
        border: 0 !important;
        background: #e3e3e3 !important;
        z-index: 9999999 !important;
    }
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
      <meta charset="utf-8">
      <title>JS Bin</title>
    </head>
    <body>
      <div>
        <p>Hello</p>
        <button onclick="inject()">Inject</button>
      </div>
    </body>
    </html>

    【讨论】:

      【解决方案2】:

      有什么理由不在 body 上使用 padding-top?另外如果你没有特殊原因,不要直接在js中添加css。而是在 css 中应用一个类并定位它。这是jsbin

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-06-11
        • 2015-12-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多