12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HTMLとCSSとJavascriptで右クリックメニューを作成する

Last updated at Posted at 2022-11-22

右クリックメニューをHTMLとCSSとJavascriptで作る

【ソースコード】

index.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>右クリックメニュー</title>
</head>
</body>
<div class="contextmenu">
        <div>コピー</div>
        <hr>
        <div>戻る</div>
        <div>進む</div>
        <div>再読み込み</div>
</div>
<!-- 本文 -->
<div class="wrapper">
    <h1>Hello World!</h1>
    <ul>
        <li>リスト1</li>
        <li>リスト2</li>
        <li>リスト3</li>
        <li>リスト4</li>
    </ul>
</div>
</body>
style.css
* {
    margin: 0;
    padding: 0;
}

.contextmenu {
    position: fixed;
    z-index: 99;
    background: #fff;
    color: #555;
    font-size: 11px;
    user-select: none;
    box-shadow: 2px 2px 2px 0 #8f9091;
    border: 1px solid #c6c6c6;
    padding: 0;
    padding-top: 4px;
    padding-bottom: 4px;
    margin: 0;
    outline: 0;
    display: none;
}

.contextmenu div {
    box-sizing: border-box;
    display: block;
    padding: 8px 8px 8px 28px;
    width: 250px;
    position: relative;
    cursor: default;
    font-size: 11px;
    font-family: sans-serif;
}

.contextmenu div:hover {
    background: #ebebeb;
}

.contextmenu hr {
    border: 1px solid #e9e9e9;
    border-bottom: 0;
    margin-top: 5px;
    margin-bottom: 5px;
}
const contextmenu = document.querySelector('.contextmenu');
const wrapper = document.querySelector('.wrapper');

wrapper.addEventListener('contextmenu', (e) => {
    contextmenu.style.left = e.pageX + 'px';
    contextmenu.style.top = e.pageY - scrollY + 'px';
    contextmenu.style.display = 'block';
});

wrapper.addEventListener('click', () => {
    contextmenu.style.display = 'none';
});

コピペ使用OKです!多少のバグは自分で直してください
(参考: https://www.sejuku.net/blog/92015)

プレビュー

See the Pen Untitled by sandoitti (@sandoitti) on CodePen.

12
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?