Series is introduced

You wish the world, I wish you no bugs. Hello everyone! I’m Lin Dull!

Dull shares seven front-end problems every week, and the series is called “DD 7 Questions per week”.

The form of the series is mainly: 3 JavaScript + 2 HTML + 2 CSS, to help us consolidate the front-end foundation.

All topics will also be integrated into the issues of LinDaiDai/ Niubility -coding-js. You are welcome to provide better ideas for solving problems. Thank you 😁.

To the chase

Design a method to extract all key-value pairs in an object whose value is greater than 2 and return the latest object

Implementation:

var obj = { a: 1.b: 3.c: 4 }
foo(obj) // { b: 3, c: 4 }
Copy the code

There are several ways to do this, but here’s a simpler way to do it, using ES10’s object.fromentries () :

var obj = { a: 1.b: 3.c: 4 }
function foo (obj) {
  return Object.fromEntries(
    Object.entries(obj).filter(([key, value]) = > value > 2)
  )
} var obj2 = foo(obj) // { b: 3, c: 4 } console.log(obj2) Copy the code
// ES8 object.entries () does:
var obj = { a: 1.b: 2 }
var entries = Object.entries(obj); // [['a', 1], ['b', 2]]
// ES10 object.fromentries ()
Object.fromEntries(entries); // { a: 1, b: 2 }
Copy the code

Github.com/LinDaiDai/n…

Implement a padStart() or padEnd() polyfill

String. Prototype. PadStart and String. Prototype. PadEnd ES8 is added in method, allows you to an empty String or other String is added to the beginning or end of the original String. Let’s look at the usage syntax first:

String.padStart(targetLength,[padString])
Copy the code

Usage:

'x'.padStart(4.'ab') // 'abax'
'x'.padEnd(5.'ab') // 'xabab'

// 1. If the input target length is less than the original length of the string, return the string itself
'xxx'.padStart(2.'s') // 'xxx'
 // 2. The default value of the second argument is "", and the length is 1 // 3. This parameter may be a string of indefinite length. If the content to be filled reaches the target length, the unwanted part will be truncated 'xxx'.padStart(5.'sss') // ssxxx  // 4. Can be used to deal with date and amount formatting problems '12'.padStart(10.'YYYY-MM-DD') // "YYYY-MM-12" '09-12'.padStart(10.'YYYY-MM-DD') // "YYYY-09-12" Copy the code

Polyfill implementation:

String.prototype.myPadStart = function (targetLen, padString = "") {
  if(! targetLen) {    throw new Error('Please enter the length you want to fill in');
  }
  let originStr = String(this); // Get the String of the call. Since this is originally String{}, we need to convert it to a String
 let originLen = originStr.length; // The original length of the string to call  if (originLen >= targetLen) return originStr; // Return the original string if the original > target  let diffNum = targetLen - originLen; // 10-6 // difference  for (let i = 0; i < diffNum; i++) { // Add a few members  for (let j = 0; j < padString.length; j++) { // The length of the padString entered may not be 1  if (originStr.length === targetLen) break; // Determine whether the target length is reached after each addition  originStr = `${padString[j]}${originStr}`;  }  if (originStr.length === targetLen) break;  }  return originStr; } console.log('xxx'.myPadStart(16)) console.log('xxx'.padStart(16)) Copy the code

${padString[j]}${orignStr}} in the second for loop.

Github.com/LinDaiDai/n…

Write a method using the re to get the value in the cookie based on name

function getCookie(name) {
  var match = document.cookie.match(new RegExp('(^| )' + name + '= (/ ^; *) '));
  if (match) return unescape(match[2]);
}
Copy the code
  1. To get a cookie on a page, you can use a document. Cookie.
'username=lindaidai; user-id=12345; user-roles=home, me, setting'
Copy the code

You can see the following information:

  • Each cookie is created byname=valueIt’s stored in this form
  • Each item may begin with an empty string' '(e.g.,username“, or an empty string' '(e.g.,user-idIt begins with)
  • Each use";"To distinguish between
  • If there are multiple values in an item, this is true","To connect (e.guser-rolesThe value of the)
  • The end of each term might be";"(such asusername“) or not (e.guser-rolesAt the end of the)
  1. So let’s break up the re here:
  • '(^| )'That means getting the beginning of each term, because we know if^Not on[]The words in the. So here(^| )The meaning of is actually split into(^)Match of representationusernameIn this case, it is an empty string with nothing in front of it(^)Understood as a^There’s another hidden one behind it' '); while|This is or this is a""(To matchuser-idAt the beginning)
  • +name+There’s nothing to tell
  • = (/ ^; *)So this is going to match=The value of the following, for examplelindaidai; Has just said^If on[]The words in"Everything but the ^ matches."“, which means right and wrong. So here([^;] *)That means in addition to";"This string matches everything else (*Match 0 or more times.
  • Some big guy equals sign is written like this'= (/ ^; (*). | $) 'And finally why can'(; | $) 'To omit? Because actually the last onecookieItem is not'; 'Phi, so it can merge with phi= (/ ^; *)This step.
  1. The last thing I getmatchIt’s actually an array of length four. Such as:
[
  "username=lindaidai;".  "".  "lindaidai".  ";"
] Copy the code
  • Item 0: full
  • Item 1: The beginning
  • Item 2: Intermediate value
  • Item 3: Ending

So we’re going to get the value of match[2].

  1. In case you get a value of%xxxSuch a sequence of characters needs to be usedunescape()Method decode.

Github.com/LinDaiDai/n…

4, implement a drag and drop (compatible writing method)

Investigate knowledge points

  1. eventThe compatibility of
  • Other Browserswindow.event
  • Not in Firefoxwindow.event, so use the parameters passed inevInstead of
  • Final writing:var oEvent = ev || window.event
  1. What events implement drag and drop (boxFor elements that need to be dragged)
  • box.onmousedown
  • document.onmousemove
  • document.onmouseup
  1. The sequence of events implemented
  • First of all to monitorbox.onmousedown, that is, the mouse is pressedboxRecords the distance from the top and left of the screen when the mouse is pressed down, andboxThe distance from the top of the screen to the left is subtracted to get the differencedistanceXanddistanceY
  • Then listen in this eventdocument.onmousemoveEvent, record the distance to the top and left of the screen for each mouse movement, and subtract themdistanceXanddistanceY, and assign it toboxtheleftandtopSo that it can follow the mouse movement
  • But you have to considerboxThe distance from the top/bottom/left/right edge of the screen
  • whendocument.onmouseupWill need to bedocument.onmousemoveEvent set tonull

As shown in the figure:


Coding

css

<style>
  html.body {
    margin: 0;
    height: 100%;
 }  #box {  width: 100px;  height: 100px;  background-color: red;  position: absolute;  top: 100px;  left: 100px;  } </style> Copy the code

html

<div id="box"></div>
Copy the code

javascript

window.onload = function () {
  var box = document.getElementById('box');
  box.onmousedown = function (ev) {
    var oEvent = ev || window.event; // Compatible with Firefox, firefox has no window.event
    var distanceX = oEvent.clientX - box.offsetLeft; // Distance from the mouse to the left of the viewable area - distance from the box to the left of the page
 var distanceY = oEvent.clientY - box.offsetTop;  document.onmousemove = function (ev) {  var oEvent = ev || window.event;  var left = oEvent.clientX - distanceX;  var top = oEvent.clientY - distanceY;  if (left <= 0) {  left = 0;  } else if (left >= document.documentElement.clientWidth - box.offsetWidth) {  left = document.documentElement.clientWidth - box.offsetWidth;  }  if (top <= 0) {  top = 0;  } else if (top >= document.documentElement.clientHeight - box.offsetHeight) {  top = document.documentElement.clientHeight - box.offsetHeight;  }  box.style.left = left + 'px';  box.style.top = top + 'px';  }  document.onmouseup = function () {  document.onmousemove = null;  document.onmouseup = null;  }  } } Copy the code

(Thanks to Turbo328 for pointing out that Document. onmouseup works better than Box.onmouseup.)

Github.com/LinDaiDai/n…

How to prevent bubbling and default events

To prevent bubbling:

function stopBubble (e) { // Prevent bubbling
  if (e && e.stopPropagation) {
    e.stopPropagation();
  } else {
    / / compatible with IE
 window.event.cancelBubble = true;  } } function stopDefault (e) { // Block the default event  if (e && e.preventDefault) {  e.preventDefault();  } else {  / / compatible with IE  window.event.returnValue = false;  return false;  } } Copy the code

Github.com/LinDaiDai/n…

Six, how to draw fan? A triangle?

/ * fan * /
.sector {
  width: 0;
  height: 0;
  border: 100px solid red;
 border-color: red transparent transparent transparent;  border-radius: 50%; } / * or * / .sector {  width: 100px;  height: 100px;  border: 100px solid transparent;  border-top-color: red;  box-sizing: border-box; /* This step is important */  border-radius: 50%; } Copy the code
/* Triangle */
.triangle {
  width: 0;
  height: 0;
  border: 100px solid red;
 border-color: red transparent transparent transparent; } / * or * / .triangle {  width: 100px;  height: 100px;  border: 100px solid transparent;  border-top-color: red;  box-sizing: border-box; } Copy the code

Github.com/LinDaiDai/n…

Seven, round? Half round? The oval?

div {
  width: 100px;
  height: 100px;
  background-color: red;
  margin-top: 20px;
} .box1 { /* 圆 */  /* border-radius: 50%; * /  border-radius: 50px; } .box2 { / * semicircle * /  height: 50px;  border-radius: 50px 50px 0 0; } .box3 { / * * / ellipses  height: 50px;  border-radius: 50px/25px; /* x /y */ } Copy the code

Github.com/LinDaiDai/n…

After the language

You wish the world, I wish you no bugs. So much for this article.

You may spend 48 hours a week at work 💻, 49 hours at sleep 😴, and maybe another 20 minutes at 7 questions, which accumulate over a long period of time. I believe we can all witness each other’s growth 😊.

What? You ask me why the series is called DD? Because dull ah, ha ha 😄.

The guy who likes “Lin Dull” also wants to follow Lin dull’s official account LinDaiDai or scan the following QR code 👇👇👇.


I will update some front-end knowledge content and my original article 🎉 from time to time

Your encouragement is the main motivation for my continuous creation 😊.

This article is formatted using MDNICE