2015-10-05 15 views
1

我想單擊按鈕時將工具欄注入到主體。它應該固定在頂部,即使用戶向下滾動時也應保持在那裏。我在移動身體時遇到了一些問題,因爲工具欄覆蓋了一些主體內容並在頂部留下了空白區域。這裏是我的代碼將工具欄div插入到頁面並向下推動主體

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標籤外添加div。我不想使用iframe,只是一個div。我將如何做到這一點?這是一個JSbin鏈接。

回答

1

在這裏,修復了代碼。您使用JavaScript在身體標記上應用了錯誤的CSS。這種變化是JavaScript的唯一

function inject() { 
 

 
\t //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); 
 

 

 
\t $('body').css({ 
 
    \t 'padding-top':'35px', 
 
    \t 'transition': 'transform 0.4s ease' 
 
\t }); 
 

 

 
    
 
}
#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>

+0

它工作。非常感謝你。 – detweiller

0

任何理由不使用填充頂在身上?另外如果你沒有特別的理由,不要直接在js中添加css。而是應用一個類,並在CSS中的目標。這是一個jsbin

相關問題