在网站 Logo 上右击时提示下载网站的 Logo 素材下载

1,193 阅读1分钟
原文链接: css-tricks.com
本文已经翻译成中文《在网站 Logo 上右击时提示下载网站的 Logo 素材下载》,欢迎参加「掘金翻译计划」,翻译优质的技术文章。

I was on the Invision website the other day and I wanted to snag their logo for some reason or another. Sometimes you can have better luck doing that (like when you happily discover it's SVG) than you can Google Image Searching or even regular web searching for something like "Invision Logo" and loping to find some kind of branding page with a logo kit download.

So I right-clicked their logo, hoping to "inspect" it with the DevTools and check it out.

Rather than showing me a context menu, it triggered a modal:

I was pleasantly surprised, because that's exactly what I wanted.

Here's a simple zero-dependencies way to do that

See the Pen Right Click Logo to Show Logo Options by Chris Coyier (@chriscoyier) on CodePen.

See the Pen <a href="http://codepen.io/chriscoyier/pen/QNyeVd/">Right Click Logo to Show Logo Options</a> by Chris Coyier (<a href="http://codepen.io/chriscoyier">@chriscoyier</a>) on <a href="http://codepen.io">CodePen</a>.

Your app might already have a whole fancy system for showing modals. If so, then it's even easier. Attach a "right click" event (it's actually called contextmenu) to the logo and do your thing.

logo.addEventListener('contextmenu', function(event) {
  // do whatever you do to show a modal
}, false);

If you don't have a modal system in place, it's very easy to make a rudimentary one. You need an overlay and a modal element:

Looking for our logo?

You clever thing. We've prepared a .zip you can download.

Close

And a plan:

  1. When the logo is right-clicked, show the overlay and modal
  2. When the close button is clicked, hide them

No problem:

var logo = document.querySelector("#logo");
var button = document.querySelector("#close-modal-button");
var overlay = document.querySelector("#overlay");
var modal = document.querySelector("#modal");

logo.addEventListener('contextmenu', function(event) {
  event.preventDefault();
  overlay.classList.add("show");
  modal.classList.add("show");
}, false);

button.addEventListener('click', function(event) {
  event.preventDefault();
  overlay.classList.remove("show");
  modal.classList.remove("show");
}, false);

Bare bones styling:

.overlay {
  position: fixed;
  background: rgba(0, 0, 0, 0.75);
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: none;
}
.overlay.show {
  display: block;
}

.modal {
  position: fixed;
  left: 50%;
  width: 300px;
  margin-left: -150px;
  top: 100px;
  background: white;
  padding: 20px;
  text-align: center;
  display: none;
}
.modal.show {
  display: block;
}
.modal > h3 {
  font-size: 26px;
  color: #900;
}

Never EVER break the default context menu and override with your own custom behavior OMG what are you an evil troll you should have never been born

You're right! Oh god what have I done! Nothing can ever change! Murderous screams!!