html tool

显示标签为“js”的博文。显示所有博文
显示标签为“js”的博文。显示所有博文

2022年4月24日星期日

js的向上向下取整

 https://blog.csdn.net/bytxl/article/details/30059107

Javascript整除运算

整除四舍五入: X=Math.round(A/B)      

整除向上取整: X=Math.ceil(A/B)

整除向下取整: X=Math.floor(A/B)

小数点后保留n位: X=X.toFixed(n)


参考:https://blog.csdn.net/mandagod/article/details/79071159

向下取整的运算称为Floor,用数学符号⌊⌋表示;向上取整的运算称为Ceiling,用数学符号⌈⌉表示。例如:

⌊59/60⌋=0


⌈59/60⌉=1


⌊-59/60⌋=-1


⌈-59/60⌉=0

2021年8月11日星期三

转:js动态添加div

 https://blog.csdn.net/zcn596785154/article/details/78055250


CSS样式文件search_history.css


div{

    width:95%;

    height:40px;

    line-height:36px;/**设置行高和控件高一样,这是内部文字才能垂直居中*/

    overflow:hidden;/**为了防止内容超出容器或者产生自动换行,这样就达不到垂直居中效果了*/

    margin: 0 auto;/**让div在页面中居中显示*/

    background-color:#ffffff;/**背景颜色*/

    border:solid 1px #f5f5f5;

    border-width:1px 0px 0px 1px;

}


p{

    margin-left:2.5%;

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

HTML页面search_history.html


<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/html">

<head>

    <meta http-equiv="content-type" content="search_history.html; charset=utf-8">

    <title>历史记录html</title>

    //引入css样式

    <link type="test/css" rel="stylesheet" href="search_history.css"/>

</head>

<body id ="test" bgcolor="#f5f5f5">

<p>历史搜索</p>

<script type="text/javascript">

    var Shu =7;

    var df = document.createDocumentFragment();

    for (var i=0;i<= Shu;i++){

    var oDiv = document.createElement("div");


    var img = document.createElement("img");

    img.src = 'ic_search_history_clock.png';

    img.style.verticalAlign="middle";//设置图片垂直居中显示

    img.style.padding="5px";

    oDiv.appendChild(img);


    var text = document.createElement("span");

    text.innerHTML = "方向盘套";

    text.style.padding="5px";

    oDiv.appendChild(text);


    var img2 = document.createElement("img");

    img2.src = 'ic_search_history_next.png';


    img2.style.verticalAlign="middle";//设置图片垂直居中显示

    img2.style.padding="5px";

    oDiv.appendChild(img2);


    df.appendChild(oDiv);

    }

    document.body.appendChild(df);

 </script>

</body>

</html>


2018年6月25日星期一

转:d3做直方图

http://www.voidcn.com/article/p-fghptgsp-bhu.html



<meta charset="utf-8">
<style>

  body {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    position: relative;
    width: 960px;
  }

  .axis text {
    font: 10px sans-serif;
  }

  .axis path,
  .axis line {
    fill: none;
    stroke: #000;
    shape-rendering: crispEdges;
  }

  .bar {
    fill: steelblue;
    fill-opacity: .9;
    text-anchor: start;
  }


  label {
    position: absolute;
    top: 10px;
    right: 10px;
  }

</style>

<body>
<label><input type="checkbox"> Sort values</label>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>

  var margin = {top: 50, right: 20, bottom: 30, left: 40},
      width = 960 - margin.left - margin.right,
      height = 700 - margin.top - margin.bottom;

  var x = d3.scale.linear()
         .rangeRound([0, width]);
  var y = d3.scale.ordinal()
          .rangeRoundBands([0, height], .5, .3);

  var xAxis = d3.svg.axis()
      .scale(x)
      .orient("top")

  var yAxis = d3.svg.axis()
      .scale(y)
      .orient("left");



  var svg = d3.select("body").append("svg")
      .attr("width", width + margin.left + margin.right)
      .attr("height", height + margin.top + margin.bottom)
      .append("g")
      .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


  var data = 
    [
      {"letter" : "A" , "frequency" : 4167},
      {"letter" : "B" , "frequency" : 6167},
      {"letter" : "C" , "frequency" : 3167},
      {"letter" : "D" , "frequency" : 5127},
      {"letter" : "E" , "frequency" : 2167},
      {"letter" : "F" , "frequency" : 8167},
      {"letter" : "G" , "frequency" : 3167},
      {"letter" : "H" , "frequency" : 9167}
    ];


   y.domain(data.map(function(d) { return d.letter; }));
   x.domain([0, d3.max(data, function(d) { return d.frequency; })]);

  svg.append("g")
    .attr("class", "x axis")
    .call(xAxis)
    .append("text")
    .attr("x", width-80)
    .attr("dy", ".81em")
    .style("font" ,"10px sans-serif")
    .style("text-anchor", "begin")
    .text("Frequency");

  svg.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate("+0 + ",0)")
    .call(xAxis);


  svg.append("g")
    .attr("class", "y axis")
    .attr("transform", "translate(0 ,0)")
    .call(yAxis);


  svg.selectAll(".bar")
    .data(data)
    .enter()    
    .append("rect")
    .attr("class", "bar")
    .attr("x", 5)
    .attr("width",function(d) { return x(d.frequency);})
    .attr("y", function(d) { return y(d.letter); })
    .attr("height", y.rangeBand())
    .on("mouseover", hyper_mouse)
    .on("click", hyper); 
 
  d3.select("input")
    .on("change", change);

  var sortTimeout = setTimeout(function() {
    d3.select("input").property("checked", false).each(change);
  }, 2000);

  function hyper(d){
    location.href="#";
  }

  function hyper_mouse(d){
    $('.bar').hover(function() {
       $(this).css('cursor','pointer');
    });
  }

  function change() {
    clearTimeout(sortTimeout);
    // Copy-on-write since tweens are evaluated after a delay.
    var x0 = y.domain(data.sort(this.checked
        ? function(a, b) { return b.frequency - a.frequency; }
        : function(a, b) { return d3.ascending(a.letter, b.letter); })
        .map(function(d) { return d.letter; }))
        .copy();

    svg.selectAll(".bar")
        .sort(function(a, b) { return x0(a.letter) - x0(b.letter); });

    var transition = svg.transition().duration(750),
        delay = function(d, i) { return i * 50; };

    transition.selectAll(".bar")
        .delay(delay)
        .attr("y", function(d) { return x0(d.letter); });

    transition.select(".y.axis")
        .call(yAxis)
      .selectAll("g")
        .delay(delay);
  }

</script>
</body>

2018年1月26日星期五

转:js-filter去空行的方式



[popexizhi:
看js时发现一种奇怪的写法关于filter,
                  var n = e.split("\n").filter(function(e) {
                        return e
                    })
发现是用来去重复和空值的很好用,原因go了一下,记录如下:)
]

参考:http://selfcontroller.iteye.com/blog/1889424


第二种: 
Js代码  收藏代码
  1. var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];  
  2. arr = arr.filter(function(n){return n}); // (javascript 1.6 and above)  
  3. arr // [1, 2, 3, 3, 4, 4, 5, 6]  


以上方法用的是javascrript的filter函数,用法: 
Js代码  收藏代码
  1. var filteredArray = array.filter(callback);  

对数组中的每个元素都执行一次指定的函数(callback),并且创建一个新的数组,该数组元素是所有回调函数执行时返回值为 true 的原数组元素。它只对数组中的非空元素执行指定的函数,没有赋值或者已经删除的元素将被忽略,同时,新创建的数组也不会包含这些元素。就是说,这个函数会利用已有的数组元素来创建新的数组,但是新的数组中的元素只能是已有数组中非空的元素或者已经赋值的元素。 

2017年12月11日星期一

javascript str replace 全部替换



http://www.w3school.com.cn/jsref/jsref_replace.asp

例子 2

在本例中,我们将执行一次全局替换,每当 "Microsoft" 被找到,它就被替换为 "W3School":

输出:
Welcome to W3School! We are proud to announce that W3School
has one of the largest Web Developers sites in the world.

2017年11月6日星期一

js 中动态加载文件后,绘制不同的dygraphs


js 中动态加载文件后,绘制不同的dygraphs

参考:
http://www.runoob.com/js/js-output.html
http://developer.51cto.com/art/201009/226006.htm
------------------------------

https://github.com/popexizhi/learning_and_thinking/blob/master/js/eg/testLoadFileX.html


2017年11月5日星期日

js的几个推荐库学习

google D3 Demo时,find this :

http://www.zcfy.cc/article/learn-to-create-d3-js-data-visualizations-by-example-913.html

作者推荐了js学习的几个基本库
我建议每个 web程序员都该学学这3个JavaScript库:jQeury,Underscore以及D3。这些库使你学会通过新的角度来看待代码:jQuery让你能通过少量代码,在DOM上做比以往更多的事,Underscore(或lodash)给你一些工具,改变了你写程序的方式,D3给了你一个丰富的工具集,以便操作数据和编程绘图。如果你对D3不熟悉,请务必花点时间看看这个震撼的例子画廊,看看D3都能做些什么。

this is better for me .note it
for learning  Demo list ,like

http://www.w3school.com.cn/jquery/jquery_ajax_load.asp
https://www.w3schools.com/jquery/

https://www.w3cways.com/doc/underscore/

2017年8月22日星期二

js只修改url不重新加载的方式



参考:http://www.yduba.com/qianduan-2421711779.html
在ajax页面修改url为当前地址的方式:

比如:现在浏览器的地址是:http://www.study.com/index.html,想让浏览器跳转到其它地址,只需要很简单的一句:
var stateObj = { foo: "bar" };
history.pushState(stateObj, "", "bar.html");
运行之后,发现浏览器地址变了,页面内容并没有刷新,如图:(直接用的 chrome 操作)
若水GIF截图_2017年2月17日16点0分28秒.gif

2017年7月26日星期三

js + 正则

替换============================================
http://www.w3school.com.cn/jsref/jsref_replace.asp
实例
例子 1
在本例中,我们将使用 "W3School" 替换字符串中的 "Microsoft":


var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/, "W3School"))


输出:
Visit W3School!
例子 2
在本例中,我们将执行一次全局替换,每当 "Microsoft" 被找到,它就被替换为 "W3School":


var str="Welcome to Microsoft! "
str=str + "We are proud to announce that Microsoft has "
str=str + "one of the largest Web Developers sites in the world."

document.write(str.replace(/Microsoft/g, "W3School"))


输出:
Welcome to W3School! We are proud to announce that W3School
has one of the largest Web Developers sites in the world.




查找===========================================
http://www.w3school.com.cn/jsref/jsref_search.asp
实例
例子 1
在本例中,我们将检索 "W3School":


var str="Visit W3School!"
document.write(str.search(/W3School/))


输出:
6
在下面的例子中,无法检索到 w3school(因为 search() 对大小写敏感)。


var str="Visit W3School!"
document.write(str.search(/w3school/))


输出:
-1
例子 2
在本例中,我们将执行一次忽略大小写的检索:


var str="Visit W3School!"
document.write(str.search(/w3school/i))


输出:
6



js try



https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError
处理空id
133             try {
134                 document.getElementById(arr[i].key).innerHTML = out ;
135             } catch (e) {                                    
136                   console.log(e instanceof TypeError); // true
137                   console.log(e.message);              // "null has no properties"
138                   console.log(e.name);                 // "TypeError"
139                   console.log(e.fileName);             // "Scratchpad/1"
140                   console.log(e.lineNumber);           // 2  
141                   console.log(e.columnNumber);         // 2  
142                   console.log(e.stack);                // "@Scratchpad/2:2:3\n"
143             }    
144         }        


Examples

Catching a TypeError

try {
  null.f();
} catch (e) {
  console.log(e instanceof TypeError); // true
  console.log(e.message);              // "null has no properties"
  console.log(e.name);                 // "TypeError"
  console.log(e.fileName);             // "Scratchpad/1"
  console.log(e.lineNumber);           // 2
  console.log(e.columnNumber);         // 2
  console.log(e.stack);                // "@Scratchpad/2:2:3\n"
}

js-post-demo


https://stackoverflow.com/questions/9713058/send-post-data-using-xmlhttprequest



accepted
This code demonstrates on how to do this.

Here is just the listing from that page, in case the above link goes down again:
var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);
    }
}
http.send(params);

2017年2月16日星期四

dygraphs 同步控制不同数据

使用dygraphs 测试同步控制不同数据图的demo成功了,改造来源如下:
官方地址testcase :http://dygraphs.com/tests/synchronize.html
测试代码提交到备份如下:
https://github.com/popexizhi/learning_and_thinking/tree/master/js/jquery/synchronize.html
[popexizhi:
1.测试过程从 https://github.com/danvk/dygraphs/tree/2.0.0-release-fixes 下载源码直接使用test中的Demo访问不成功,:)忘记编译了,官方文档说的很清楚要求:
npm install
npm run build
js项目下载使用也要编译啊:)实在不想编译的话到
http://dygraphs.com/tests/synchronize.html 
保存对应的直接js,css依赖才可以使用的
2.测试不同文件使用不同的坐标系,页面定位是和坐标内容一起移动的,没有的位置会补充空白,
很不错的效果赞一个
]

2015年2月25日星期三

js的拾遗



1.Re-Declaring JavaScript Variables
  • If you re-declare a JavaScript variable, it will not lose its value.
    The variable carName will still have the value "Volvo" after the execution of these statements:
    Example
    var carName = "Volvo";
    var carName;
    PS:这个应该是重新定义时没有初始化对应的内存区吧,是编译器和语言的要求吗?!
    2.Example
    var x = "5" + 2 + 3;
    Note:If you add a number to a string, the number will be treated as string, and concatenated.
    3.JavaScript evaluates expressions from left to right. Different sequences can produce different results:
    ---------------------------
    JavaScript:
    var x = 16 + 4 + "Volvo";
    Result:
    20Volvo
    ---------------------
    JavaScript:
    var x = "Volvo" + 16 + 4;
    Result:
    Volvo164
    [popexizhi:从左到右的啊!
    测试了一下
    var x =10+4+"Volvo"+20*3;
    Result:
    14Volvo60
    应该是按运算符顺序计算,但遇到字符串后变成字符串运算的。
    ]

    4.typeof
    The typeof Operator
    You can use the JavaScript typeof operator to find the type of a JavaScript variable:
    Example
    typeof "John"                // Returns string
    typeof 3.14                  // Returns number
    typeof false                 // Returns boolean
    typeof [1,2,3,4]             // Returns object
    typeof {name:'John', age:34} // Returns object
    5.----
    Undefined
    In JavaScript, a variable without a value, has the value undefined. The typeof is also undefined.
    Example
    var person;                  // The value is undefined, the typeof is undefined